Merge branch 'master' into Fix/stream-issues

pull/938/head
harshalmore31 4 months ago committed by GitHub
commit ff7324a7a9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -11,7 +11,7 @@ jobs:
permissions: write-all
runs-on: ubuntu-latest
steps:
- uses: actions/first-interaction@v2.0.0
- uses: actions/first-interaction@v3.0.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
issue-message:

@ -1,6 +1,8 @@
from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
import orjson
from dotenv import load_dotenv
from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
load_dotenv()
swarm = AutoSwarmBuilder(
@ -8,10 +10,11 @@ swarm = AutoSwarmBuilder(
description="My Swarm Description",
verbose=True,
max_loops=1,
return_agents=True,
)
result = swarm.run(
task="Build a swarm to write a research paper on the topic of AI"
)
print(result)
print(orjson.dumps(result, option=orjson.OPT_INDENT_2).decode())

@ -1,13 +0,0 @@
1. make agent api - fastapi
2. make agent cron job
3. agents that listen that could listen to events
4. run on startup, every time the machine starts
4. docker
5. kubernetes
6. aws or google cloud etc
user -> build agent -> user now need deploy agent
FAST

@ -0,0 +1,57 @@
# Advanced Research
An enhanced implementation of the orchestrator-worker pattern from Anthropic's paper, "How we built our multi-agent research system", built on top of the bleeding-edge multi-agent framework [swarms](https://github.com/kyegomez/swarms). Our implementation of this advanced research system leverages parallel execution, LLM-as-judge evaluation, and professional report generation with export capabilities.
**Repository**: [AdvancedResearch](https://github.com/The-Swarm-Corporation/AdvancedResearch)
## Installation
```bash
pip3 install -U advanced-research
# uv pip install -U advanced-research
```
## Environment Variables
```txt
# Exa Search API Key (Required for web search functionality)
EXA_API_KEY="your_exa_api_key_here"
# Anthropic API Key (For Claude models)
ANTHROPIC_API_KEY="your_anthropic_api_key_here"
# OpenAI API Key (For GPT models)
OPENAI_API_KEY="your_openai_api_key_here"
# Worker Agent Configuration
WORKER_MODEL_NAME="gpt-4.1"
WORKER_MAX_TOKENS=8000
# Exa Search Configuration
EXA_SEARCH_NUM_RESULTS=2
EXA_SEARCH_MAX_CHARACTERS=100
```
**Note**: At minimum, you need `EXA_API_KEY` for web search functionality. For LLM functionality, you need either `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`.
## Quick Start
### Basic Usage
```python
from advanced_research import AdvancedResearch
# Initialize the research system
research_system = AdvancedResearch(
name="AI Research Team",
description="Specialized AI research system",
max_loops=1,
)
# Run research and get results
result = research_system.run(
"What are the latest developments in quantum computing?"
)
print(result)
```

@ -0,0 +1,111 @@
# Browser Automation with Swarms
This example demonstrates how to use browser automation capabilities within the Swarms framework. The `BrowserUseAgent` class provides a powerful interface for web scraping, navigation, and automated browser interactions using the `browser_use` library. This is particularly useful for tasks that require real-time web data extraction, form filling, or web application testing.
## Install
```bash
pip3 install -U swarms browser-use python-dotenv langchain-openai
```
## Environment Variables
```txt
# OpenAI API Key (Required for LLM functionality)
OPENAI_API_KEY="your_openai_api_key_here"
```
## Main Code
```python
import asyncio
from browser_use import Agent as BrowserAgent
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from swarms import Agent
load_dotenv()
class BrowserUseAgent:
def __init__(self, agent_name: str = "BrowserAgent", agent_description: str = "A browser agent that can navigate the web and perform tasks."):
"""
Initialize a BrowserAgent with a given name.
Args:
agent_name (str): The name of the browser agent.
"""
self.agent_name = agent_name
self.agent_description = agent_description
async def browser_agent_test(self, task: str):
"""
Asynchronously run the browser agent on a given task.
Args:
task (str): The task prompt for the agent.
Returns:
Any: The result of the agent's run method.
"""
agent = BrowserAgent(
task=task,
llm=ChatOpenAI(model="gpt-4.1"),
)
result = await agent.run()
return result.model_dump_json(indent=4)
def run(self, task: str):
"""
Run the browser agent synchronously on a given task.
Args:
task (str): The task prompt for the agent.
Returns:
Any: The result of the agent's run method.
"""
return asyncio.run(self.browser_agent_test(task))
def browser_agent_tool(task: str):
"""
Executes a browser automation agent as a callable tool.
This function instantiates a `BrowserAgent` and runs it synchronously on the provided task prompt.
The agent will use a language model to interpret the task, control a browser, and return the results
as a JSON-formatted string.
Args:
task (str):
A detailed instruction or prompt describing the browser-based task to perform.
For example, you can instruct the agent to navigate to a website, extract information,
or interact with web elements.
Returns:
str:
The result of the browser agent's execution, formatted as a JSON string. The output
typically includes the agent's findings, extracted data, and any relevant observations
from the automated browser session.
Example:
result = browser_agent_tool(
"Please navigate to https://www.coingecko.com and identify the best performing cryptocurrency coin over the past 24 hours."
)
print(result)
"""
return BrowserAgent().run(task)
agent = Agent(
name = "Browser Agent",
model_name = "gpt-4.1",
tools = [browser_agent_tool],
)
agent.run("Please navigate to https://www.coingecko.com and identify the best performing cryptocurrency coin over the past 24 hours.")
```

@ -0,0 +1,48 @@
# Web Search with Exa
Exa is a powerful web search API that provides real-time access to current web information. It allows AI agents to search the internet and retrieve up-to-date information on any topic, making it an essential tool for agents that need current knowledge beyond their training data.
Key features of Exa:
| Feature | Description |
|--------------------------|--------------------------------------------------------------------|
| **Real-time search** | Access the latest information from the web |
| **Semantic search** | Find relevant results using natural language queries |
| **Comprehensive coverage** | Search across billions of web pages |
| **Structured results** | Get clean, formatted search results for easy processing |
| **API integration** | Simple REST API for seamless integration with AI applications |
## Install
```bash
pip3 install -U swarms swarms-tools
```
## ENV
```txt
# Get your API key from exa
EXA_SEARCH_API=""
OPENAI_API_KEY=""
WORKSPACE_DIR=""
```
## Code
```python
from swarms import Agent
from swarms_tools import exa_search
agent = Agent(
name="Exa Search Agent",
llm="gpt-4o-mini",
tools=[exa_search],
)
out = agent.run("What are the latest experimental treatments for diabetes?")
print(out)
```

File diff suppressed because it is too large Load Diff

@ -375,18 +375,24 @@ nav:
- Agent Output Types: "swarms/examples/agent_output_types.md"
- Gradio Chat Interface: "swarms/ui/main.md"
- LLM Providers:
- Overview: "swarms/examples/model_providers.md"
- OpenAI: "swarms/examples/openai_example.md"
- Anthropic: "swarms/examples/claude.md"
- Groq: "swarms/examples/groq.md"
- Cohere: "swarms/examples/cohere.md"
- DeepSeek: "swarms/examples/deepseek.md"
- Ollama: "swarms/examples/ollama.md"
- OpenRouter: "swarms/examples/openrouter.md"
- XAI: "swarms/examples/xai.md"
- Azure OpenAI: "swarms/examples/azure.md"
- VLLM: "swarms/examples/vllm_integration.md"
- Llama4: "swarms/examples/llama4.md"
- Language Models:
- How to Create A Custom Language Model: "swarms/models/custom_model.md"
- Overview: "swarms/examples/model_providers.md"
- OpenAI: "swarms/examples/openai_example.md"
- Anthropic: "swarms/examples/claude.md"
- Groq: "swarms/examples/groq.md"
- Cohere: "swarms/examples/cohere.md"
- DeepSeek: "swarms/examples/deepseek.md"
- Ollama: "swarms/examples/ollama.md"
- OpenRouter: "swarms/examples/openrouter.md"
- XAI: "swarms/examples/xai.md"
- Azure OpenAI: "swarms/examples/azure.md"
- VLLM: "swarms/examples/vllm_integration.md"
- Llama4: "swarms/examples/llama4.md"
- MultiModal Models:
- BaseMultiModalModel: "swarms/models/base_multimodal_model.md"
- Multi Modal Models Available: "swarms/models/multimodal_models.md"
- GPT4VisionAPI: "swarms/models/gpt4v.md"
@ -418,66 +424,43 @@ nav:
- Swarms DAO: "swarms/examples/swarms_dao.md"
- Swarms of Browser Agents: "swarms/examples/swarms_of_browser_agents.md"
- ConcurrentWorkflow with VLLM Agents: "swarms/examples/vllm.md"
- Tools & Integrations:
- Web Search with Exa: "examples/exa_search.md"
- Advanced Research: "examples/av.md"
- Browser Use: "examples/browser_use.md"
- Yahoo Finance: "swarms/examples/yahoo_finance.md"
- Apps:
- Smart Database: "examples/smart_database.md"
# - Swarm Models:
# - Overview: "swarms/models/index.md"
# # - Models Available: "swarms/models/index.md"
# # - Available Models from OpenAI, Huggingface, TogetherAI, and more: "swarms/models/models_available_overview.md"
# # - Model Router
# - Quickstart: "swarms/models/models_available_overview.md"
# - How to Create A Custom Language Model: "swarms/models/custom_model.md"
# - Language Models:
# - BaseLLM: "swarms/models/base_llm.md"
# - HuggingFaceLLM: "swarms/models/huggingface.md"
# - Anthropic: "swarms/models/anthropic.md"
# - OpenAIChat: "swarms/models/openai.md"
# - OpenAIFunctionCaller: "swarms/models/openai_function_caller.md"
# - Groq: "swarms/models/groq.md"
# - Cerebras: "swarms/models/cerebras.md"
# - MultiModal Models:
# - BaseMultiModalModel: "swarms/models/base_multimodal_model.md"
# - Multi Modal Models Available: "swarms/models/multimodal_models.md"
# - GPT4VisionAPI: "swarms/models/gpt4v.md"
- Swarms Cloud API:
- Overview: "swarms_cloud/swarms_api.md"
- Quickstart: "swarms_cloud/quickstart.md"
- MCP Server: "swarms_cloud/mcp.md"
- Rate Limits: "swarms_cloud/rate_limits.md"
- Best Practices: "swarms_cloud/best_practices.md"
- Capabilities:
- Agents:
- Individual Agent Completions: "swarms_cloud/agent_api.md"
- Tools: "swarms_cloud/swarms_api_tools.md"
- Multi-Agent:
- Multi Agent Architectures Available: "swarms_cloud/swarm_types.md"
- Swarm Types:
- AgentRearrange: "swarms_cloud/agent_rearrange.md"
- MixtureOfAgents: "swarms_cloud/mixture_of_agents.md"
- SequentialWorkflow: "swarms_cloud/sequential_workflow.md"
- ConcurrentWorkflow: "swarms_cloud/concurrent_workflow.md"
- GroupChat: "swarms_cloud/group_chat.md"
- MultiAgentRouter: "swarms_cloud/multi_agent_router.md"
- HierarchicalSwarm: "swarms_cloud/hierarchical_swarm.md"
- MajorityVoting: "swarms_cloud/majority_voting.md"
# - AutoSwarmBuilder: "swarms_cloud/auto_swarm_builder.md"
# - Auto: "swarms_cloud/auto.md"
- Examples:
- Medical Swarm: "swarms/examples/swarms_api_medical.md"
- Finance Swarm: "swarms/examples/swarms_api_finance.md"
- Clients:
- Overview: "swarms_cloud/api_clients.md"
- Python Client: "swarms_cloud/python_client.md"
- Rust Client: "swarms_cloud/rust_client.md"
- Pricing:
- Pricing: "swarms_cloud/api_pricing.md"
- Subscription Tiers: "swarms_cloud/subscription_tiers.md"
- Overview: "swarms_cloud/migration.md"
# - Capabilities:
# - Agents:
# - Individual Agent Completions: "swarms_cloud/agent_api.md"
# - Tools: "swarms_cloud/swarms_api_tools.md"
# - Multi-Agent:
# - Multi Agent Architectures Available: "swarms_cloud/swarm_types.md"
# - Swarm Types:
# - AgentRearrange: "swarms_cloud/agent_rearrange.md"
# - MixtureOfAgents: "swarms_cloud/mixture_of_agents.md"
# - SequentialWorkflow: "swarms_cloud/sequential_workflow.md"
# - ConcurrentWorkflow: "swarms_cloud/concurrent_workflow.md"
# - GroupChat: "swarms_cloud/group_chat.md"
# - MultiAgentRouter: "swarms_cloud/multi_agent_router.md"
# - HierarchicalSwarm: "swarms_cloud/hierarchical_swarm.md"
# - MajorityVoting: "swarms_cloud/majority_voting.md"
# # - AutoSwarmBuilder: "swarms_cloud/auto_swarm_builder.md"
# # - Auto: "swarms_cloud/auto.md"
# - Examples:
# - Medical Swarm: "swarms/examples/swarms_api_medical.md"
# - Finance Swarm: "swarms/examples/swarms_api_finance.md"
- Swarms Marketplace:
- Overview: "swarms_platform/index.md"
@ -508,8 +491,3 @@ nav:
- Architecture & Design:
- Understanding Swarms Architecture: "swarms/concept/framework_architecture.md"
- Development Philosophy & Principles: "swarms/concept/philosophy.md"
# - About Swarms:
# - Vision & Mission: "swarms/concept/vision.md"
# - Swarm Ecosystem: "swarms/concept/swarm_ecosystem.md"
# - Products: "swarms/products.md"

@ -122,24 +122,13 @@ load_dotenv()
yaml_file = "agents_multi_agent.yaml"
# 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,
)
try:
# Create agents and run tasks (using 'both' to return agents and task results)
task_results = create_agents_from_yaml(
model=model, yaml_file=yaml_file, return_type="run_swarm"
)
# Create agents and run tasks (using 'both' to return agents and task results)
task_results = create_agents_from_yaml(
model=model, yaml_file=yaml_file, return_type="run_swarm"
)
logger.info(f"Results from agents: {task_results}")
logger.info(f"Results from agents: {task_results}")
except Exception as e:
logger.error(f"An error occurred: {e}")

@ -1,17 +1,12 @@
# Agents Introduction
The Agent class is the core component of the Swarms framework, designed to create intelligent, autonomous AI agents capable of handling complex tasks through multi-modal processing, tool integration, and structured outputs. This comprehensive guide covers all aspects of the Agent class, from basic setup to advanced features.
## Table of Contents
An agent in swarms is basically 4 elements added together:
`agent = LLM + Tools + RAG + Loop`
The Agent class is the core component of the Swarms framework, designed to create intelligent, autonomous AI agents capable of handling complex tasks through multi-modal processing, tool integration, and structured outputs. This comprehensive guide covers all aspects of the Agent class, from basic setup to advanced features.
1. [Prerequisites & Installation](#prerequisites--installation)
2. [Basic Agent Configuration](#basic-agent-configuration)
3. [Multi-Modal Capabilities](#multi-modal-capabilities)
4. [Tool Integration](#tool-integration)
5. [Structured Outputs](#structured-outputs)
6. [Advanced Features](#advanced-features)
7. [Best Practices](#best-practices)
8. [Complete Examples](#complete-examples)
## Prerequisites & Installation
@ -492,57 +487,6 @@ final_only_agent = Agent(
)
```
### Safety and Content Filtering
```python
from swarms import Agent
# Agent with enhanced safety features
safe_agent = Agent(
agent_name="Safe-Agent",
agent_description="Agent with comprehensive safety measures",
system_prompt="You are a helpful, harmless, and honest AI assistant.",
model_name="gpt-4o-mini",
safety_prompt_on=True, # Enable safety prompts
max_loops=1,
temperature=0.3 # Lower temperature for more consistent, safe responses
)
```
## Best Practices
### Error Handling and Robustness
```python
import logging
from swarms import Agent
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def robust_agent_execution(agent, task, max_retries=3):
"""Execute agent with retry logic and error handling."""
for attempt in range(max_retries):
try:
response = agent.run(task)
logger.info(f"Agent execution successful on attempt {attempt + 1}")
return response
except Exception as e:
logger.error(f"Attempt {attempt + 1} failed: {str(e)}")
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt) # Exponential backoff
return None
# Example usage
try:
result = robust_agent_execution(agent, "Analyze market trends")
print(result)
except Exception as e:
print(f"Agent execution failed: {e}")
```
### Performance Optimization
@ -869,15 +813,13 @@ If you encounter issues or need assistance:
We welcome contributions! Here's how to get involved:
- **Report Bugs**: Help us improve by reporting issues
- **Suggest Features**: Share your ideas for new capabilities
- **Submit Code**: Contribute improvements and new features
- **Improve Documentation**: Help make our docs better
- **Share Examples**: Show how you're using Swarms in your projects
| Contribution Type | Description |
|-------------------------|--------------------------------------------------|
| **Report Bugs** | Help us improve by reporting issues |
| **Suggest Features** | Share your ideas for new capabilities |
| **Submit Code** | Contribute improvements and new features |
| **Improve Documentation** | Help make our docs better |
| **Share Examples** | Show how you're using Swarms in your projects |
---

@ -9,8 +9,6 @@
```python
import os
from swarm_models import OpenAIChat
from swarms import Agent
company = "NVDA"

@ -1,12 +1,31 @@
# Swarms Tools Example with Yahoo Finance
# Yahoo Finance Integration with Swarms
- `pip3 install swarms swarms-tools`
- Add `OPENAI_API_KEY` to your `.env` file
- Run `yahoo_finance_agent.py`
- Agent will make a function call to the desired tool
- The tool will be executed and the result will be returned to the agent
- The agent will then analyze the result and return the final output
This example demonstrates how to integrate Yahoo Finance data into your Swarms agents using the `swarms-tools` package. The agent can analyze real-time financial data, stock metrics, and market information by making function calls to the Yahoo Finance API. This is particularly useful for financial analysis, portfolio management, and market research applications.
## Install
```bash
pip3 install -U swarms swarms-tools
```
## Environment Variables
```txt
# OpenAI API Key (Required for LLM functionality)
OPENAI_API_KEY="your_openai_api_key_here"
```
## Usage
1. Install the required packages
2. Add your `OPENAI_API_KEY` to your `.env` file
3. Run the example code below
4. The agent will make a function call to the Yahoo Finance tool
5. The tool will execute and return financial data
6. The agent analyzes the result and provides insights
## Code Example
```python
from swarms import Agent
@ -24,19 +43,12 @@ agent = Agent(
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o",
dynamic_temperature_enabled=True,
user_name="swarms_corp",
retry_attempts=3,
context_length=8192,
return_step_meta=False,
output_type="str", # "json", "dict", "csv" OR "string" "yaml" and
auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task
max_tokens=4000, # max output tokens
saved_state_path="agent_00.json",
interactive=False,
tools=[yahoo_finance_api],
)
# Run financial analysis
agent.run("Analyze the latest metrics for nvidia")
# Less than 30 lines of code....
```
```
**Result**: Less than 30 lines of code to get a fully functional financial analysis agent!

@ -1,6 +1,6 @@
# `AgentRearrange` Class
The `AgentRearrange` class represents a swarm of agents for rearranging tasks. It allows you to create a swarm of agents, add or remove agents from the swarm, and run the swarm to process tasks based on a specified flow pattern.
The `AgentRearrange` class represents a swarm of agents for rearranging tasks. It allows you to create a swarm of agents, add or remove agents from the swarm, and run the swarm to process tasks based on a specified flow pattern. The class now includes **sequential awareness** features that allow agents to know about the agents ahead and behind them in sequential flows.
## Attributes
----------
@ -17,26 +17,38 @@ The `AgentRearrange` class represents a swarm of agents for rearranging tasks. I
| `memory_system` | `BaseVectorDatabase` | Memory system for storing agent interactions |
| `human_in_the_loop` | `bool` | Whether human intervention is enabled |
| `custom_human_in_the_loop` | `Callable` | Custom function for human intervention |
| `return_json` | `bool` | Whether to return output in JSON format |
| `output_type` | `OutputType` | Format of output ("all", "final", "list", or "dict") |
| `docs` | `List[str]` | List of document paths to add to agent prompts |
| `doc_folder` | `str` | Folder path containing documents to add to agent prompts |
| `swarm_history` | `dict` | History of agent interactions |
| `autosave` | `bool` | Whether to automatically save agent data |
| `rules` | `str` | Custom rules to add to the conversation |
| `team_awareness` | `bool` | Whether to enable team awareness and sequential flow information |
| `time_enabled` | `bool` | Whether to enable timestamps in conversation |
| `message_id_on` | `bool` | Whether to enable message IDs in conversation |
## Methods
-------
### `__init__(self, agents: List[Agent] = None, flow: str = None, max_loops: int = 1, verbose: bool = True)`
### `__init__(self, id: str = swarm_id(), name: str = "AgentRearrange", description: str = "A swarm of agents for rearranging tasks.", agents: List[Union[Agent, Callable]] = None, flow: str = None, max_loops: int = 1, verbose: bool = True, memory_system: Any = None, human_in_the_loop: bool = False, custom_human_in_the_loop: Optional[Callable[[str], str]] = None, output_type: OutputType = "all", autosave: bool = True, rules: str = None, team_awareness: bool = False, time_enabled: bool = False, message_id_on: bool = False, *args, **kwargs)`
Initializes the `AgentRearrange` object.
Initializes the `AgentRearrange` object with enhanced sequential awareness capabilities.
| Parameter | Type | Description |
| --- | --- | --- |
| `agents` | `List[Agent]` (optional) | A list of `Agent` objects. Defaults to `None`. |
| `id` | `str` (optional) | Unique identifier for the swarm. Defaults to auto-generated UUID. |
| `name` | `str` (optional) | Name of the swarm. Defaults to "AgentRearrange". |
| `description` | `str` (optional) | Description of the swarm's purpose. Defaults to "A swarm of agents for rearranging tasks.". |
| `agents` | `List[Union[Agent, Callable]]` (optional) | A list of `Agent` objects or callables. Defaults to `None`. |
| `flow` | `str` (optional) | The flow pattern of the tasks. Defaults to `None`. |
| `max_loops` | `int` (optional) | The maximum number of loops for the agents to run. Defaults to `1`. |
| `verbose` | `bool` (optional) | Whether to enable verbose logging or not. Defaults to `True`. |
| `memory_system` | `Any` (optional) | Memory system for storing agent interactions. Defaults to `None`. |
| `human_in_the_loop` | `bool` (optional) | Whether human intervention is enabled. Defaults to `False`. |
| `custom_human_in_the_loop` | `Callable[[str], str]` (optional) | Custom function for human intervention. Defaults to `None`. |
| `output_type` | `OutputType` (optional) | Format of output. Defaults to `"all"`. |
| `autosave` | `bool` (optional) | Whether to automatically save agent data. Defaults to `True`. |
| `rules` | `str` (optional) | Custom rules to add to the conversation. Defaults to `None`. |
| `team_awareness` | `bool` (optional) | Whether to enable team awareness and sequential flow information. Defaults to `False`. |
| `time_enabled` | `bool` (optional) | Whether to enable timestamps in conversation. Defaults to `False`. |
| `message_id_on` | `bool` (optional) | Whether to enable message IDs in conversation. Defaults to `False`. |
### `add_agent(self, agent: Agent)`
@ -74,54 +86,130 @@ Validates the flow pattern.
- `bool`: `True` if the flow pattern is valid.
### `run(self, task: str = None, img: str = None, device: str = "cpu", device_id: int = 1, all_cores: bool = True, all_gpus: bool = False, *args, **kwargs)`
### **Sequential Awareness Methods**
#### `get_agent_sequential_awareness(self, agent_name: str) -> str`
Gets the sequential awareness information for a specific agent, showing which agents come before and after in the sequence.
| Parameter | Type | Description |
| --- | --- | --- |
| `agent_name` | `str` | The name of the agent to get awareness for. |
**Returns:**
- `str`: A string describing the agents ahead and behind in the sequence.
**Example:**
```python
awareness = agent_system.get_agent_sequential_awareness("Agent2")
# Returns: "Sequential awareness: Agent ahead: Agent1 | Agent behind: Agent3"
```
#### `get_sequential_flow_structure(self) -> str`
Gets the overall sequential flow structure information showing the complete workflow with relationships between agents.
**Returns:**
- `str`: A string describing the complete sequential flow structure.
**Example:**
```python
flow_structure = agent_system.get_sequential_flow_structure()
# Returns: "Sequential Flow Structure:
# Step 1: Agent1
# Step 2: Agent2 (follows: Agent1) (leads to: Agent3)
# Step 3: Agent3 (follows: Agent2)"
```
### `run(self, task: str = None, img: str = None, *args, **kwargs)`
Executes the agent rearrangement task with specified compute resources.
| Parameter | Type | Description |
| --- | --- | --- |
| `task` | `str` | The task to execute |
| `img` | `str` | Path to input image if required |
| `device` | `str` | Computing device to use ('cpu' or 'gpu') |
| `device_id` | `int` | ID of specific device to use |
| `all_cores` | `bool` | Whether to use all CPU cores |
| `all_gpus` | `bool` | Whether to use all available GPUs |
| `task` | `str` (optional) | The task to execute. Defaults to `None`. |
| `img` | `str` (optional) | Path to input image if required. Defaults to `None`. |
| `*args` | - | Additional positional arguments passed to `_run()`. |
| `**kwargs` | - | Additional keyword arguments passed to `_run()`. |
**Returns:**
- `str`: The final processed task.
- The result from executing the task through the cluster operations wrapper.
### `batch_run(self, tasks: List[str], img: Optional[List[str]] = None, batch_size: int = 10, device: str = "cpu", device_id: int = None, all_cores: bool = True, all_gpus: bool = False, *args, **kwargs)`
### `batch_run(self, tasks: List[str], img: Optional[List[str]] = None, batch_size: int = 10, *args, **kwargs)`
Process multiple tasks in batches.
| Parameter | Type | Description |
| --- | --- | --- |
| `tasks` | `List[str]` | List of tasks to process |
| `img` | `List[str]` | Optional list of images corresponding to tasks |
| `img` | `List[str]` (optional) | Optional list of images corresponding to tasks |
| `batch_size` | `int` | Number of tasks to process simultaneously |
| `device` | `str` | Computing device to use |
| `device_id` | `int` | Specific device ID if applicable |
| `all_cores` | `bool` | Whether to use all CPU cores |
| `all_gpus` | `bool` | Whether to use all available GPUs |
| `*args` | - | Additional positional arguments |
| `**kwargs` | - | Additional keyword arguments |
**Returns:**
- `List[str]`: List of results corresponding to input tasks
### `concurrent_run(self, tasks: List[str], img: Optional[List[str]] = None, max_workers: Optional[int] = None, device: str = "cpu", device_id: int = None, all_cores: bool = True, all_gpus: bool = False, *args, **kwargs)`
### `concurrent_run(self, tasks: List[str], img: Optional[List[str]] = None, max_workers: Optional[int] = None, *args, **kwargs)`
Process multiple tasks concurrently using ThreadPoolExecutor.
| Parameter | Type | Description |
| --- | --- | --- |
| `tasks` | `List[str]` | List of tasks to process |
| `img` | `List[str]` | Optional list of images corresponding to tasks |
| `max_workers` | `int` | Maximum number of worker threads |
| `device` | `str` | Computing device to use |
| `device_id` | `int` | Specific device ID if applicable |
| `all_cores` | `bool` | Whether to use all CPU cores |
| `all_gpus` | `bool` | Whether to use all available GPUs |
| `img` | `List[str]` (optional) | Optional list of images corresponding to tasks |
| `max_workers` | `int` (optional) | Maximum number of worker threads |
| `*args` | - | Additional positional arguments |
| `**kwargs` | - | Additional keyword arguments |
**Returns:**
- `List[str]`: List of results corresponding to input tasks
## **Sequential Awareness Feature**
The `AgentRearrange` class now includes a powerful **sequential awareness** feature that enhances agent collaboration in sequential workflows. When agents are executed sequentially, they automatically receive information about:
- **Agent ahead**: The agent that completed their task before them
- **Agent behind**: The agent that will receive their output next
This feature is automatically enabled when using sequential flows and provides agents with context about their position in the workflow, improving coordination and task understanding.
### How It Works
1. **Automatic Detection**: The system automatically detects when agents are running sequentially vs. in parallel
2. **Context Injection**: Before each sequential agent runs, awareness information is added to the conversation
3. **Enhanced Collaboration**: Agents can reference previous agents' work and prepare output for the next agent
### Example with Sequential Awareness
```python
from swarms import Agent, AgentRearrange
# Create agents
agent1 = Agent(agent_name="Researcher", system_prompt="Research the topic")
agent2 = Agent(agent_name="Writer", system_prompt="Write based on research")
agent3 = Agent(agent_name="Editor", system_prompt="Edit the written content")
# Create sequential workflow
workflow = AgentRearrange(
agents=[agent1, agent2, agent3],
flow="Researcher -> Writer -> Editor",
team_awareness=True # Enables sequential awareness
)
# Run the workflow
result = workflow.run("Research and write about artificial intelligence")
```
**What happens automatically:**
- **Researcher** runs first (no awareness info needed)
- **Writer** receives: "Sequential awareness: Agent ahead: Researcher | Agent behind: Editor"
- **Editor** receives: "Sequential awareness: Agent ahead: Writer"
## Documentation for `rearrange` Function
======================================
@ -133,9 +221,12 @@ The `rearrange` function is a helper function that rearranges the given list of
| Parameter | Type | Description |
| --- | --- | --- |
| `name` | `str` (optional) | Name for the agent system. Defaults to `None`. |
| `description` | `str` (optional) | Description for the agent system. Defaults to `None`. |
| `agents` | `List[Agent]` | The list of agents to be rearranged. |
| `flow` | `str` | The flow used for rearranging the agents. |
| `task` | `str` (optional) | The task to be performed during rearrangement. Defaults to `None`. |
| `img` | `str` (optional) | Path to input image if required. Defaults to `None`. |
| `*args` | - | Additional positional arguments. |
| `**kwargs` | - | Additional keyword arguments. |
@ -157,7 +248,7 @@ rearrange(agents, flow, task)
### Example Usage
-------------
Here's an example of how to use the `AgentRearrange` class and the `rearrange` function:
Here's an example of how to use the `AgentRearrange` class and the `rearrange` function with the new sequential awareness features:
```python
from swarms import Agent, AgentRearrange
@ -211,20 +302,35 @@ agents = [director, worker1, worker2]
# Define the flow pattern
flow = "Accounting Director -> Accountant 1 -> Accountant 2"
# Using AgentRearrange class
agent_system = AgentRearrange(agents=agents, flow=flow)
# Using AgentRearrange class with sequential awareness
agent_system = AgentRearrange(
agents=agents,
flow=flow,
team_awareness=True, # Enables sequential awareness
time_enabled=True, # Enable timestamps
message_id_on=True # Enable message IDs
)
# Get sequential flow information
flow_structure = agent_system.get_sequential_flow_structure()
print("Flow Structure:", flow_structure)
# Get awareness for specific agents
worker1_awareness = agent_system.get_agent_sequential_awareness("Accountant 1")
print("Worker1 Awareness:", worker1_awareness)
# Run the workflow
output = agent_system.run("Process monthly financial statements")
print(output)
```
In this example, we first initialize three agents: `director`, `worker1`, and `worker2`. Then, we create a list of these agents and define the flow pattern `"Director -> Worker1 -> Worker2"`.
We can use the `AgentRearrange` class by creating an instance of it with the list of agents and the flow pattern. We then call the `run` method with the initial task, and it will execute the agents in the specified order, passing the output of one agent as the input to the next agent.
Alternatively, we can use the `rearrange` function by passing the list of agents, the flow pattern, and the initial task as arguments.
Both the `AgentRearrange` class and the `rearrange` function will return the final output after processing the task through the agents according to the specified flow pattern.
The new sequential awareness features provide:
- **Automatic context**: Each agent knows who came before and who comes after
- **Better coordination**: Agents can reference previous work and prepare for next steps
- **Flow visualization**: You can see the complete workflow structure
- **Enhanced logging**: Better tracking of agent interactions
## Error Handling
--------------
@ -242,63 +348,69 @@ output = agent_system.run("Some task")`
This will raise a `ValueError` with the message `"Agent 'Worker3' is not registered."`.
## Parallel and Sequential Processing
----------------------------------
The `AgentRearrange` class supports both parallel and sequential processing of tasks based on the specified flow pattern. If the flow pattern includes multiple agents separated by commas (e.g., `"agent1, agent2"`), the agents will be executed in parallel, and their outputs will be concatenated with a semicolon (`;`). If the flow pattern includes a single agent, it will be executed sequentially.
The `AgentRearrange` class supports both parallel and sequential processing of tasks based on the specified flow pattern. If the flow pattern includes multiple agents separated by commas (e.g., `"agent1, agent2"`), the agents will be executed in parallel, and their outputs will be concatenated. If the flow pattern includes a single agent, it will be executed sequentially with enhanced awareness.
### Parallel processing
`parallel_flow = "Worker1, Worker2 -> Director"`
### Sequential processing
### Sequential processing with awareness
`sequential_flow = "Worker1 -> Worker2 -> Director"`
In the `parallel_flow` example, `Worker1` and `Worker2` will be executed in parallel, and their outputs will be concatenated and passed to `Director`. In the `sequential_flow` example, `Worker1` will be executed first, and its output will be passed to `Worker2`, and then the output of `Worker2` will be passed to `Director`.
In the `parallel_flow` example, `Worker1` and `Worker2` will be executed in parallel, and their outputs will be concatenated and passed to `Director`.
## Logging
-------
In the `sequential_flow` example, `Worker1` will be executed first, then `Worker2` will receive awareness that `Worker1` came before and `Director` comes after, and finally `Director` will receive awareness that `Worker2` came before.
The `AgentRearrange` class includes logging capabilities using the `loguru` library. If `verbose` is set to `True` during initialization, a log file named `agent_rearrange.log` will be created, and log messages will be written to it. You can use this log file to track the execution of the agents and any potential issues or errors that may occur.
## Logging and Monitoring
-------
The `AgentRearrange` class includes comprehensive logging capabilities using the `loguru` library. The new sequential awareness features add enhanced logging:
```bash
2023-05-08 10:30:15.456 | INFO | agent_rearrange:__init__:34 - Adding agent Director to the swarm.
2023-05-08 10:30:15.457 | INFO | agent_rearrange:__init__:34 - Adding agent Worker1 to the swarm.
2023-05-08 10:30:15.457 | INFO | agent_rearrange:__init__:34 - Adding agent Worker2 to the swarm.
2023-05-08 10:30:15.458 | INFO | agent_rearrange:run:118 - Running agents in parallel: ['Worker1', 'Worker2']
2023-05-08 10:30:15.459 | INFO | agent_rearrange:run:121 - Running agents sequentially: ['Director']`
2023-05-08 10:30:15.459 | INFO | agent_rearrange:run:121 - Running agents sequentially: ['Director']
2023-05-08 10:30:15.460 | INFO | agent_rearrange:run:125 - Added sequential awareness for Worker2: Sequential awareness: Agent ahead: Worker1 | Agent behind: Director
```
## Additional Parameters
---------------------
The `AgentRearrange` class also accepts additional parameters that can be passed to the `run` method using `*args` and `**kwargs`. These parameters will be forwarded to the individual agents during execution.
`agent_system = AgentRearrange(agents=agents, flow=flow)`
`output = agent_system.run("Some task", max_tokens=200, temperature=0.7)`
The `AgentRearrange` class now accepts additional parameters for enhanced functionality:
In this example, the `max_tokens` and `temperature` parameters will be passed to each agent during execution.
```python
agent_system = AgentRearrange(
agents=agents,
flow=flow,
team_awareness=True, # Enable sequential awareness
time_enabled=True, # Enable conversation timestamps
message_id_on=True, # Enable message IDs
verbose=True # Enable detailed logging
)
```
## Customization
-------------
The `AgentRearrange` class and the `rearrange` function can be customized and extended to suit specific use cases. For example, you can create custom agents by inheriting from the `Agent` class and implementing custom logic for task processing. You can then add these custom agents to the swarm and define the flow pattern accordingly.
Additionally, you can modify the `run` method of the `AgentRearrange` class to implement custom logic for task processing and agent interaction.
The `AgentRearrange` class and the `rearrange` function can be customized and extended to suit specific use cases. The new sequential awareness features provide a foundation for building more sophisticated agent coordination systems.
## Limitations
-----------
It's important to note that the `AgentRearrange` class and the `rearrange` function rely on the individual agents to process tasks correctly. The quality of the output will depend on the capabilities and configurations of the agents used in the swarm. Additionally, the `AgentRearrange` class does not provide any mechanisms for task prioritization or load balancing among the agents.
It's important to note that the `AgentRearrange` class and the `rearrange` function rely on the individual agents to process tasks correctly. The quality of the output will depend on the capabilities and configurations of the agents used in the swarm.
The sequential awareness feature works best with agents that can understand and utilize context about their position in the workflow.
## Conclusion
----------
The `AgentRearrange` class and the `rearrange` function provide a flexible and extensible framework for orchestrating swarms of agents to process tasks based on a specified flow pattern. By combining the capabilities of individual agents, you can create complex workflows and leverage the strengths of different agents to tackle various tasks efficiently.
The `AgentRearrange` class and the `rearrange` function provide a flexible and extensible framework for orchestrating swarms of agents to process tasks based on a specified flow pattern. The new **sequential awareness** features significantly enhance agent collaboration by providing context about workflow relationships.
By combining the capabilities of individual agents with enhanced awareness of their position in the workflow, you can create more intelligent and coordinated multi-agent systems that understand not just their individual tasks, but also their role in the larger workflow.
While the current implementation offers basic functionality for agent rearrangement, there is room for future improvements and customizations to enhance the system's capabilities and cater to more specific use cases.
Whether you're working on natural language processing tasks, data analysis, or any other domain where agent-based systems can be beneficial, the enhanced `AgentRearrange` class provides a solid foundation for building sophisticated swarm-based solutions with improved coordination and context awareness.
Whether you're working on natural language processing tasks, data analysis, or any other domain where agent-based systems can be beneficial, the `AgentRearrange` class and the `rearrange` function provide a solid foundation for building and experimenting with swarm-based solutions.

@ -32,24 +32,6 @@ A production-grade multi-agent system enabling sophisticated group conversations
| max_loops | int | 10 | Maximum conversation turns |
## Table of Contents
- [Installation](#installation)
- [Core Concepts](#core-concepts)
- [Basic Usage](#basic-usage)
- [Advanced Configuration](#advanced-configuration)
- [Speaker Functions](#speaker-functions)
- [Response Models](#response-models)
- [Advanced Examples](#advanced-examples)
- [API Reference](#api-reference)
- [Best Practices](#best-practices)
## Installation
```bash
pip3 install swarms swarm-models loguru
```
## Core Concepts
The GroupChat system consists of several key components:
@ -65,55 +47,23 @@ The GroupChat system consists of several key components:
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,
model_name="gpt-4.1",
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,
model_name="gpt-4.1",
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]
@ -212,36 +162,6 @@ chat = GroupChat(
)
```
## Response Models
### Complete Schema
```python
class AgentResponse(BaseModel):
"""Individual agent response in a conversation turn"""
agent_name: str
role: str
message: str
timestamp: datetime = Field(default_factory=datetime.now)
turn_number: int
preceding_context: List[str] = Field(default_factory=list)
class ChatTurn(BaseModel):
"""Single turn in the conversation"""
turn_number: int
responses: List[AgentResponse]
task: str
timestamp: datetime = Field(default_factory=datetime.now)
class ChatHistory(BaseModel):
"""Complete conversation history"""
turns: List[ChatTurn]
total_messages: int
name: str
description: str
start_time: datetime = Field(default_factory=datetime.now)
```
## Advanced Examples
### Multi-Agent Analysis Team
@ -251,19 +171,19 @@ class ChatHistory(BaseModel):
data_analyst = Agent(
agent_name="Data-Analyst",
system_prompt="You analyze numerical data and patterns",
llm=model
model_name="gpt-4.1",
)
market_expert = Agent(
agent_name="Market-Expert",
system_prompt="You provide market insights and trends",
llm=model
model_name="gpt-4.1",
)
strategy_advisor = Agent(
agent_name="Strategy-Advisor",
system_prompt="You formulate strategic recommendations",
llm=model
model_name="gpt-4.1",
)
# Create analysis team
@ -308,29 +228,12 @@ for task, history in zip(tasks, histories):
## Best Practices
1. **Agent Design**
- Give agents clear, specific roles
- Use detailed system prompts
- Set appropriate context lengths
- Enable retries for reliability
2. **Speaker Functions**
- Match function to use case
- Consider conversation flow
- Handle edge cases
- Add appropriate logging
3. **Error Handling**
- Use try-except blocks
- Log errors appropriately
- Implement retry logic
- Provide fallback responses
4. **Performance**
- Use concurrent processing for multiple tasks
- Monitor context lengths
- Implement proper cleanup
- Cache responses when appropriate
| Category | Recommendations |
|---------------------|--------------------------------------------------------------------------------------------------|
| **Agent Design** | - Give agents clear, specific roles<br>- Use detailed system prompts<br>- Set appropriate context lengths<br>- Enable retries for reliability |
| **Speaker Functions** | - Match function to use case<br>- Consider conversation flow<br>- Handle edge cases<br>- Add appropriate logging |
| **Error Handling** | - Use try-except blocks<br>- Log errors appropriately<br>- Implement retry logic<br>- Provide fallback responses |
| **Performance** | - Use concurrent processing for multiple tasks<br>- Monitor context lengths<br>- Implement proper cleanup<br>- Cache responses when appropriate |
## API Reference

@ -2,27 +2,23 @@
---
## 🚀 Benefits of Multi-Agent Collaboration
<div align="center">
<img src="/assets/img/benefits.png" alt="Benefits of Multi-Agent Collaboration" width="700"/>
<br/>
<em>Fig. 1: Key benefits and structure of multi-agent collaboration</em>
</div>
## Benefits of Multi-Agent Collaboration
### Why Multi-Agent Architectures?
Multi-agent systems unlock new levels of intelligence, reliability, and efficiency by enabling agents to work together. Here are the core benefits:
1. **Reduction of Hallucination**: Cross-verification between agents ensures more accurate, reliable outputs by reducing hallucination.
2. **Extended Memory**: Agents share knowledge and task history, achieving collective long-term memory for smarter, more adaptive responses.
3. **Specialization & Task Distribution**: Delegating tasks to specialized agents boosts efficiency and quality.
4. **Parallel Processing**: Multiple agents work simultaneously, greatly increasing speed and throughput.
5. **Scalability & Adaptability**: Systems can dynamically scale and adapt, maintaining efficiency as demands change.
| **Benefit** | **Description** |
|------------------------------------|----------------------------------------------------------------------------------------------------------------------|
| **Reduction of Hallucination** | Cross-verification between agents ensures more accurate, reliable outputs by reducing hallucination. |
| **Extended Memory** | Agents share knowledge and task history, achieving collective long-term memory for smarter, more adaptive responses. |
| **Specialization & Task Distribution** | Delegating tasks to specialized agents boosts efficiency and quality. |
| **Parallel Processing** | Multiple agents work simultaneously, greatly increasing speed and throughput. |
| **Scalability & Adaptability** | Systems can dynamically scale and adapt, maintaining efficiency as demands change. |
---
## 🏗️ Multi-Agent Architectures For Production Deployments
## Multi-Agent Architectures For Production Deployments
`swarms` provides a variety of powerful, pre-built multi-agent architectures enabling you to orchestrate agents in various ways. Choose the right structure for your specific problem to build efficient and reliable production systems.
@ -42,7 +38,7 @@ Multi-agent systems unlock new levels of intelligence, reliability, and efficien
---
### 🏢 HierarchicalSwarm Example
### HierarchicalSwarm Example
Hierarchical architectures enable structured, iterative, and scalable problem-solving by combining a director (or router) agent with specialized worker agents or swarms. Below are two key patterns:
@ -292,14 +288,14 @@ Join our community of agent engineers and researchers for technical support, cut
| Platform | Description | Link |
|----------|-------------|------|
| 📚 Documentation | Official documentation and guides | [docs.swarms.world](https://docs.swarms.world) |
| 📝 Blog | Latest updates and technical articles | [Medium](https://medium.com/@kyeg) |
| 💬 Discord | Live chat and community support | [Join Discord](https://discord.gg/EamjgSaEQf) |
| 🐦 Twitter | Latest news and announcements | [@kyegomez](https://twitter.com/kyegomez) |
| 👥 LinkedIn | Professional network and updates | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) |
| 📺 YouTube | Tutorials and demos | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) |
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/5p2jnc2v) |
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
| Documentation | Official documentation and guides | [docs.swarms.world](https://docs.swarms.world) |
| Blog | Latest updates and technical articles | [Medium](https://medium.com/@kyeg) |
| Discord | Live chat and community support | [Join Discord](https://discord.gg/EamjgSaEQf) |
| Twitter | Latest news and announcements | [@kyegomez](https://twitter.com/kyegomez) |
| LinkedIn | Professional network and updates | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) |
| YouTube | Tutorials and demos | [Swarms Channel](https://www.youtube.com/channel/UC9yXyXyitkbU_WSy7bd_41SqQ) |
| Events | Join our community events | [Sign up here](https://lu.ma/5p2jnc2v) |
| Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
---

@ -1,7 +1,5 @@
# MixtureOfAgents Class Documentation
## Architecture Overview
```mermaid
graph TD
A[Input Task] --> B[Initialize MixtureOfAgents]
@ -26,7 +24,6 @@ graph TD
end
```
## Overview
The `MixtureOfAgents` class represents a mixture of agents operating within a swarm. The workflow of the swarm follows a parallel → sequential → parallel → final output agent process. This implementation is inspired by concepts discussed in the paper: [https://arxiv.org/pdf/2406.04692](https://arxiv.org/pdf/2406.04692).
@ -73,45 +70,8 @@ class MixtureOfAgents(BaseSwarm):
| `auto_save` | `bool` | Flag indicating whether to auto-save the metadata to a file. | `False` |
| `saved_file_name`| `str` | The name of the file where the metadata will be saved. | `"moe_swarm.json"` |
### `agent_check`
```python
def agent_check(self):
```
#### Description
Checks if the provided `agents` attribute is a list of `Agent` instances. Raises a `TypeError` if the validation fails.
#### Example Usage
```python
moe_swarm = MixtureOfAgents(agents=[agent1, agent2])
moe_swarm.agent_check() # Validates the agents
```
### `final_agent_check`
```python
def final_agent_check(self):
```
#### Description
Checks if the provided `final_agent` attribute is an instance of `Agent`. Raises a `TypeError` if the validation fails.
#### Example Usage
```python
moe_swarm = MixtureOfAgents(final_agent=final_agent)
moe_swarm.final_agent_check() # Validates the final agent
```
### `swarm_initialization`
```python
def swarm_initialization(self):
```
#### Description
@ -280,48 +240,28 @@ For further reading and background information on the concepts used in the `Mixt
```python
from swarms import MixtureOfAgents, Agent
from swarm_models import OpenAIChat
# Define agents
director = Agent(
agent_name="Director",
system_prompt="Directs the tasks for the accountants",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="director.json",
)
# Initialize accountant 1
accountant1 = Agent(
agent_name="Accountant1",
system_prompt="Prepares financial statements",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="accountant1.json",
)
# Initialize accountant 2
accountant2 = Agent(
agent_name="Accountant2",
system_prompt="Audits financial records",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="accountant2.json",
)
@ -338,49 +278,28 @@ print(history)
```python
from swarms import MixtureOfAgents, Agent
from swarm_models import OpenAIChat
# Define Agents
# Define agents
director = Agent(
agent_name="Director",
system_prompt="Directs the tasks for the accountants",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="director.json",
)
# Initialize accountant 1
accountant1 = Agent(
agent_name="Accountant1",
system_prompt="Prepares financial statements",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="accountant1.json",
)
# Initialize accountant 2
accountant2 = Agent(
agent_name="Accountant2",
system_prompt="Audits financial records",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="accountant2.json",
)
# Initialize the MixtureOfAgents with verbose output and auto-save enabled
@ -401,49 +320,30 @@ print(history)
```python
from swarms import MixtureOfAgents, Agent
from swarm_models import OpenAIChat
# Define agents
# Initialize the director agent
director = Agent(
agent_name="Director",
system_prompt="Directs the tasks for the accountants",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="director.json",
)
# Initialize accountant 1
accountant1 = Agent(
agent_name="Accountant1",
system_prompt="Prepares financial statements",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="accountant1.json",
)
# Initialize accountant 2
accountant2 = Agent(
agent_name="Accountant2",
system_prompt="Audits financial records",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="accountant2.json",
)
# Initialize the MixtureOfAgents with custom rules and multiple layers
@ -468,11 +368,13 @@ The `MixtureOfAgents` class is a powerful and flexible framework for managing an
### Key Takeaways
1. **Flexible Initialization**: The class allows for customizable initialization with various parameters, enabling users to tailor the swarm's configuration to their specific needs.
2. **Robust Agent Management**: With built-in validation methods, the class ensures that all agents and the final agent are correctly instantiated, preventing runtime errors and facilitating smooth execution.
3. **Layered Processing**: The layered approach to processing allows for intermediate results to be iteratively refined, enhancing the overall output quality.
4. **Verbose Logging and Auto-Save**: These features aid in debugging, monitoring, and record-keeping, providing transparency and ease of management.
5. **Comprehensive Documentation**: The detailed class and method documentation, along with numerous usage examples, provide a clear and thorough understanding of how to leverage the `MixtureOfAgents` class effectively.
| Feature | Description |
|-----------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Flexible Initialization** | The class allows for customizable initialization with various parameters, enabling users to tailor the swarm's configuration to their specific needs. |
| **Robust Agent Management** | Built-in validation methods ensure that all agents and the final agent are correctly instantiated, preventing runtime errors and facilitating smooth execution. |
| **Layered Processing** | The layered approach to processing allows for intermediate results to be iteratively refined, enhancing the overall output quality. |
| **Verbose Logging and Auto-Save** | Features such as verbose logging and auto-save aid in debugging, monitoring, and record-keeping, providing transparency and ease of management. |
| **Comprehensive Documentation** | Detailed class and method documentation, along with numerous usage examples, provide a clear and thorough understanding of how to leverage the `MixtureOfAgents` class effectively. |
### Practical Applications
@ -499,46 +401,28 @@ In conclusion, the `MixtureOfAgents` class represents a versatile and efficient
```python
from swarms import MixtureOfAgents, Agent
from swarm_models import OpenAIChat
# Initialize agents as in previous examples
director = Agent(
agent_name="Director",
system_prompt="Directs the tasks for the accountants",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="director.json",
)
accountant1 = Agent(
agent_name="Accountant1",
system_prompt="Prepares financial statements",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="accountant1.json",
)
accountant2 = Agent(
agent_name="Accountant2",
system_prompt="Audits financial records",
llm=OpenAIChat(),
model_name="gpt-4.1",
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="accountant2.json",
)
# Initialize MixtureOfAgents
@ -562,7 +446,6 @@ for task, result in zip(tasks, results):
```python
from swarms import MixtureOfAgents, Agent
from swarm_models import OpenAIChat
# Initialize agents as before
# ... agent initialization code ...
@ -585,19 +468,3 @@ for task, result in zip(tasks, results):
print(f"Task: {task}\nResult: {result}\n")
```
## Advanced Features
### Context Preservation
The `MixtureOfAgents` class maintains context between iterations when running multiple loops. Each subsequent iteration receives the context from previous runs, allowing for more sophisticated and context-aware processing.
### Asynchronous Processing
The class implements asynchronous processing internally using Python's `asyncio`, enabling efficient handling of concurrent operations and improved performance for complex workflows.
### Telemetry and Logging
Built-in telemetry and logging capabilities help track agent performance and maintain detailed execution records:
- Automatic logging of agent outputs
- Structured data capture using Pydantic models
- JSON-formatted output options

@ -1,16 +1,12 @@
# RoundRobin: Round-Robin Task Execution in a Swarm
## Introduction
The `RoundRobinSwarm` class is designed to manage and execute tasks among multiple agents in a round-robin fashion. This approach ensures that each agent in a swarm receives an equal opportunity to execute tasks, which promotes fairness and efficiency in distributed systems. It is particularly useful in environments where collaborative, sequential task execution is needed among various agents.
## Conceptual Overview
### What is Round-Robin?
## What is Round-Robin?
Round-robin is a scheduling technique commonly used in computing for managing processes in shared systems. It involves assigning a fixed time slot to each process and cycling through all processes in a circular order without prioritization. In the context of swarms of agents, this method ensures equitable distribution of tasks and resource usage among all agents.
### Application in Swarms
## Application in Swarms
In swarms, `RoundRobinSwarm` utilizes the round-robin scheduling to manage tasks among agents like software components, autonomous robots, or virtual entities. This strategy is beneficial where tasks are interdependent or require sequential processing.
@ -28,73 +24,57 @@ In swarms, `RoundRobinSwarm` utilizes the round-robin scheduling to manage tasks
Initializes the swarm with the provided list of agents, verbosity setting, and operational parameters.
**Parameters:**
- `agents`: Optional list of agents in the swarm.
- `verbose`: Boolean flag for detailed logging.
- `max_loops`: Maximum number of execution cycles.
- `callback`: Optional function called after each loop.
| Parameter | Type | Description |
|-------------|---------------------|-----------------------------------------------------|
| agents | List[Agent], optional | List of agents in the swarm. |
| verbose | bool | Boolean flag for detailed logging. |
| max_loops | int | Maximum number of execution cycles. |
| callback | Callable, optional | Function called after each loop. |
### `run`
Executes a specified task across all agents in a round-robin manner, cycling through each agent repeatedly for the number of specified loops.
**Conceptual Behavior:**
- Distribute the task sequentially among all agents starting from the current index.
- Each agent processes the task and potentially modifies it or produces new output.
- After an agent completes its part of the task, the index moves to the next agent.
- This cycle continues until the specified maximum number of loops is completed.
- Optionally, a callback function can be invoked after each loop to handle intermediate results or perform additional actions.
| Step | Description |
|------|-------------|
| 1 | Distribute the task sequentially among all agents starting from the current index. |
| 2 | Each agent processes the task and potentially modifies it or produces new output. |
| 3 | After an agent completes its part of the task, the index moves to the next agent. |
| 4 | This cycle continues until the specified maximum number of loops is completed. |
| 5 | Optionally, a callback function can be invoked after each loop to handle intermediate results or perform additional actions. |
## Examples
### Example 1: Load Balancing Among Servers
In this example, `RoundRobinSwarm` is used to distribute network requests evenly among a group of servers. This is common in scenarios where load balancing is crucial for maintaining system responsiveness and scalability.
```python
from swarms import Agent, RoundRobinSwarm
from swarm_models import OpenAIChat
# Initialize the LLM
llm = OpenAIChat()
# Define sales agents
sales_agent1 = Agent(
agent_name="Sales Agent 1 - Automation Specialist",
system_prompt="You're Sales Agent 1, your purpose is to generate sales for a company by focusing on the benefits of automating accounting processes!",
agent_description="Generate sales by focusing on the benefits of automation!",
llm=llm,
model_name="gpt-4.1",
max_loops=1,
autosave=True,
dashboard=False,
verbose=True,
streaming_on=True,
context_length=1000,
)
sales_agent2 = Agent(
agent_name="Sales Agent 2 - Cost Saving Specialist",
system_prompt="You're Sales Agent 2, your purpose is to generate sales for a company by emphasizing the cost savings of using swarms of agents!",
agent_description="Generate sales by emphasizing cost savings!",
llm=llm,
model_name="gpt-4.1",
max_loops=1,
autosave=True,
dashboard=False,
verbose=True,
streaming_on=True,
context_length=1000,
)
sales_agent3 = Agent(
agent_name="Sales Agent 3 - Efficiency Specialist",
system_prompt="You're Sales Agent 3, your purpose is to generate sales for a company by highlighting the efficiency and accuracy of our swarms of agents in accounting processes!",
agent_description="Generate sales by highlighting efficiency and accuracy!",
llm=llm,
model_name="gpt-4.1",
max_loops=1,
autosave=True,
dashboard=False,
verbose=True,
streaming_on=True,
context_length=1000,
)
# Initialize the swarm with sales agents
@ -103,14 +83,11 @@ sales_swarm = RoundRobinSwarm(agents=[sales_agent1, sales_agent2, sales_agent3],
# Define a sales task
task = "Generate a sales email for an accountant firm executive to sell swarms of agents to automate their accounting processes."
# Distribute sales tasks to different agents
for _ in range(5): # Repeat the task 5 times
results = sales_swarm.run(task)
print("Sales generated:", results)
out = sales_swarm.run(task)
print(out)
```
## Conclusion
The RoundRobinSwarm class provides a robust and flexible framework for managing tasks among multiple agents in a fair and efficient manner. This class is especially useful in environments where tasks need to be distributed evenly among a group of agents, ensuring that all tasks are handled timely and effectively. Through the round-robin algorithm, each agent in the swarm is guaranteed an equal opportunity to contribute to the overall task, promoting efficiency and collaboration.

@ -1,44 +1,77 @@
# SequentialWorkflow Documentation
**Overview:**
A Sequential Swarm architecture processes tasks in a linear sequence. Each agent completes its task before passing the result to the next agent in the chain. This architecture ensures orderly processing and is useful when tasks have dependencies. [Learn more here in the docs:](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/)
A Sequential Swarm architecture processes tasks in a linear sequence. Each agent completes its task before passing the result to the next agent in the chain. This architecture ensures orderly processing and is useful when tasks have dependencies. The system now includes **sequential awareness** features that allow agents to know about the agents ahead and behind them in the workflow, significantly enhancing coordination and context understanding. [Learn more here in the docs:](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/)
**Use-Cases:**
- Workflows where each step depends on the previous one, such as assembly lines or sequential data processing.
- Scenarios requiring strict order of operations.
- **NEW**: Enhanced workflows where agents need context about their position in the sequence for better coordination.
```mermaid
graph TD
A[First Agent] --> B[Second Agent]
B --> C[Third Agent]
C --> D[Fourth Agent]
style A fill:#e1f5fe
style B fill:#f3e5f5
style C fill:#e8f5e8
style D fill:#fff3e0
A -.->|"Awareness: None (first)"| A
B -.->|"Awareness: Ahead: A, Behind: C"| B
C -.->|"Awareness: Ahead: B, Behind: D"| C
D -.->|"Awareness: Ahead: C, Behind: None (last)"| D
```
## **Sequential Awareness Feature**
The SequentialWorkflow now includes a powerful **sequential awareness** feature that automatically provides each agent with context about their position in the workflow:
### What Agents Know Automatically
- **Agent ahead**: The agent that completed their task before them
- **Agent behind**: The agent that will receive their output next
- **Workflow position**: Their step number and role in the sequence
### Benefits
1. **Better Coordination**: Agents can reference previous work and prepare output for the next step
2. **Context Understanding**: Each agent knows their role in the larger workflow
3. **Improved Quality**: Output is tailored for the next agent in the sequence
4. **Enhanced Logging**: Better tracking of agent interactions and workflow progress
## Attributes
| Attribute | Type | Description |
|------------------|---------------|--------------------------------------------------|
| `agents` | `List[Agent]` | The list of agents in the workflow. |
| `flow` | `str` | A string representing the order of agents. |
| `agent_rearrange`| `AgentRearrange` | Manages the dynamic execution of agents. |
| `agent_rearrange`| `AgentRearrange` | Manages the dynamic execution of agents with sequential awareness. |
| `team_awareness` | `bool` | **NEW**: Enables sequential awareness features. Defaults to `False`. |
| `time_enabled` | `bool` | **NEW**: Enables timestamps in conversation. Defaults to `False`. |
| `message_id_on` | `bool` | **NEW**: Enables message IDs in conversation. Defaults to `False`. |
## Methods
### `__init__(self, agents: List[Agent] = None, max_loops: int = 1, *args, **kwargs)`
### `__init__(self, agents: List[Agent] = None, max_loops: int = 1, team_awareness: bool = False, time_enabled: bool = False, message_id_on: bool = False, *args, **kwargs)`
The constructor initializes the `SequentialWorkflow` object.
The constructor initializes the `SequentialWorkflow` object with enhanced sequential awareness capabilities.
- **Parameters:**
- `agents` (`List[Agent]`, optional): The list of agents in the workflow. Defaults to `None`.
- `max_loops` (`int`, optional): The maximum number of loops to execute the workflow. Defaults to `1`.
- `team_awareness` (`bool`, optional): **NEW**: Enables sequential awareness features. Defaults to `False`.
- `time_enabled` (`bool`, optional): **NEW**: Enables timestamps in conversation. Defaults to `False`.
- `message_id_on` (`bool`, optional): **NEW**: Enables message IDs in conversation. Defaults to `False`.
- `*args`: Variable length argument list.
- `**kwargs`: Arbitrary keyword arguments.
### `run(self, task: str) -> str`
Runs the specified task through the agents in the dynamically constructed flow.
Runs the specified task through the agents in the dynamically constructed flow with enhanced sequential awareness.
- **Parameters:**
- `task` (`str`): The task for the agents to execute.
@ -46,10 +79,28 @@ Runs the specified task through the agents in the dynamically constructed flow.
- **Returns:**
- `str`: The final result after processing through all agents.
## **Usage Example:**
### **NEW: Sequential Awareness Methods**
```python
#### `get_agent_sequential_awareness(self, agent_name: str) -> str`
Gets the sequential awareness information for a specific agent, showing which agents come before and after in the sequence.
- **Parameters:**
- `agent_name` (`str`): The name of the agent to get awareness for.
- **Returns:**
- `str`: A string describing the agents ahead and behind in the sequence.
#### `get_sequential_flow_structure(self) -> str`
Gets the overall sequential flow structure information showing the complete workflow with relationships between agents.
- **Returns:**
- `str`: A string describing the complete sequential flow structure.
## **Usage Example with Sequential Awareness:**
```python
from swarms import Agent, SequentialWorkflow
# Initialize agents for individual tasks
@ -65,33 +116,168 @@ agent2 = Agent(
model_name="gpt-4o",
max_loops=1,
)
agent3 = Agent(
agent_name="ICD-10 Code Validator",
system_prompt="Validate and finalize the ICD-10 code recommendations.",
model_name="gpt-4o",
max_loops=1,
)
# Create the Sequential workflow
# Create the Sequential workflow with enhanced awareness
workflow = SequentialWorkflow(
agents=[agent1, agent2], max_loops=1, verbose=False
agents=[agent1, agent2, agent3],
max_loops=1,
verbose=False,
team_awareness=True, # Enable sequential awareness
time_enabled=True, # Enable timestamps
message_id_on=True # Enable message IDs
)
# Get workflow structure information
flow_structure = workflow.get_sequential_flow_structure()
print("Workflow Structure:")
print(flow_structure)
# Get awareness for specific agents
analyzer_awareness = workflow.get_agent_sequential_awareness("ICD-10 Code Analyzer")
summarizer_awareness = workflow.get_agent_sequential_awareness("ICD-10 Code Summarizer")
validator_awareness = workflow.get_agent_sequential_awareness("ICD-10 Code Validator")
print(f"\nAnalyzer Awareness: {analyzer_awareness}")
print(f"Summarizer Awareness: {summarizer_awareness}")
print(f"Validator Awareness: {validator_awareness}")
# Run the workflow
workflow.run(
result = workflow.run(
"Analyze the medical report and provide the appropriate ICD-10 codes."
)
print(f"\nFinal Result: {result}")
```
**Expected Output:**
```
Workflow Structure:
Sequential Flow Structure:
Step 1: ICD-10 Code Analyzer
Step 2: ICD-10 Code Summarizer (follows: ICD-10 Code Analyzer) (leads to: ICD-10 Code Validator)
Step 3: ICD-10 Code Validator (follows: ICD-10 Code Summarizer)
Analyzer Awareness:
Summarizer Awareness: Sequential awareness: Agent ahead: ICD-10 Code Analyzer | Agent behind: ICD-10 Code Validator
Validator Awareness: Sequential awareness: Agent ahead: ICD-10 Code Summarizer
```
## **How Sequential Awareness Works**
### 1. **Automatic Context Injection**
When `team_awareness=True`, the system automatically adds awareness information to each agent's conversation context before they run:
- **First Agent**: No awareness info (starts the workflow)
- **Middle Agents**: Receive info about both the agent ahead and behind
- **Last Agent**: Receives info about the agent ahead only
### 2. **Enhanced Agent Prompts**
Each agent receives context like:
```
Sequential awareness: Agent ahead: ICD-10 Code Analyzer | Agent behind: ICD-10 Code Validator
```
### 3. **Improved Coordination**
Agents can now:
- Reference previous work more effectively
- Prepare output specifically for the next agent
- Understand their role in the larger workflow
- Provide better context for subsequent steps
## **Advanced Usage Examples**
### **Example 1: Research → Analysis → Report Workflow**
```python
# Create specialized agents
researcher = Agent(
agent_name="Researcher",
system_prompt="Conduct thorough research on the given topic."
)
analyzer = Agent(
agent_name="Data Analyzer",
system_prompt="Analyze research data and identify key insights."
)
reporter = Agent(
agent_name="Report Writer",
system_prompt="Write comprehensive reports based on analysis."
)
# Create workflow with awareness
workflow = SequentialWorkflow(
agents=[researcher, analyzer, reporter],
team_awareness=True,
time_enabled=True
)
# Run with enhanced coordination
result = workflow.run("Research and analyze the impact of AI on healthcare")
```
This example initializes a `SequentialWorkflow` with three agents and executes a task, printing the final result.
### **Example 2: Code Review Workflow**
```python
# Create code review agents
linter = Agent(
agent_name="Code Linter",
system_prompt="Check code for syntax errors and style violations."
)
reviewer = Agent(
agent_name="Code Reviewer",
system_prompt="Review code quality and suggest improvements."
)
## **Notes:**
tester = Agent(
agent_name="Code Tester",
system_prompt="Write and run tests for the reviewed code."
)
- Logs the task execution process and handles any exceptions that occur during the task execution.
# Create workflow
workflow = SequentialWorkflow(
agents=[linter, reviewer, tester],
team_awareness=True
)
# Run code review process
result = workflow.run("Review and test the authentication module")
```
## **Notes:**
- **Enhanced Logging**: The workflow now logs sequential awareness information for better debugging and monitoring.
- **Automatic Context**: No manual configuration needed - awareness is automatically provided when `team_awareness=True`.
- **Backward Compatibility**: Existing workflows continue to work without changes.
- **Performance**: Sequential awareness adds minimal overhead while significantly improving coordination.
### Logging and Error Handling
The `run` method includes logging to track the execution flow and captures errors to provide detailed information in case of failures. This is crucial for debugging and ensuring smooth operation of the workflow.
The `run` method now includes enhanced logging to track the sequential awareness flow and captures detailed information about agent interactions:
```bash
2023-05-08 10:30:15.456 | INFO | SequentialWorkflow:run:45 - Starting sequential workflow execution
2023-05-08 10:30:15.457 | INFO | SequentialWorkflow:run:52 - Added sequential awareness for ICD-10 Code Summarizer: Sequential awareness: Agent ahead: ICD-10 Code Analyzer | Agent behind: ICD-10 Code Validator
2023-05-08 10:30:15.458 | INFO | SequentialWorkflow:run:52 - Added sequential awareness for ICD-10 Code Validator: Sequential awareness: Agent ahead: ICD-10 Code Summarizer
```
## Additional Tips
- Ensure that the agents provided to the `SequentialWorkflow` are properly initialized and configured to handle the tasks they will receive.
- **Enable Team Awareness**: Set `team_awareness=True` to unlock the full potential of sequential coordination.
- **Use Descriptive Agent Names**: Clear agent names make the awareness information more useful.
- **Monitor Logs**: Enhanced logging provides insights into how agents are coordinating.
- **Iterative Improvement**: Use the awareness features to refine agent prompts and improve workflow quality.
## **Benefits of Sequential Awareness**
- The `max_loops` parameter can be used to control how many times the workflow should be executed, which is useful for iterative processes.
1. **Improved Quality**: Agents produce better output when they understand their context
2. **Better Coordination**: Reduced redundancy and improved handoffs between agents
3. **Enhanced Debugging**: Clear visibility into agent interactions and workflow progress
4. **Scalable Workflows**: Easy to add new agents while maintaining coordination
5. **Professional Workflows**: Mimics real-world team collaboration patterns
- Utilize the logging information to monitor and debug the task execution process.
The SequentialWorkflow with sequential awareness represents a significant advancement in multi-agent coordination, enabling more sophisticated and professional workflows that closely mirror human team collaboration patterns.

@ -1,6 +1,6 @@
# SpreadSheetSwarm Documentation
---
## Class Definition
@ -189,20 +189,10 @@ swarm._save_to_csv()
```python
import os
from swarms import Agent
from swarm_models import OpenAIChat
from swarms import Agent, SpreadSheetSwarm
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm
# Example usage:
api_key = os.getenv("OPENAI_API_KEY")
# Model
model = OpenAIChat(
openai_api_key=api_key, model_name="gpt-4o-mini", temperature=0.1
)
# Initialize your agents (assuming the Agent class and model are already defined)
@ -210,7 +200,7 @@ agents = [
Agent(
agent_name=f"Financial-Analysis-Agent-spreesheet-swarm:{i}",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
llm=model,
model_name="gpt-4.1",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="finance_agent.json",
@ -242,9 +232,7 @@ swarm.run(
```python
import os
from swarms import Agent
from swarm_models import OpenAIChat
from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm
from swarms import Agent, SpreadSheetSwarm
# Define custom system prompts for QR code generation
QR_CODE_AGENT_1_SYS_PROMPT = """
@ -255,20 +243,13 @@ QR_CODE_AGENT_2_SYS_PROMPT = """
You are a Python coding expert. Your task is to write a Python script to generate a QR code for the link: https://github.com/The-Swarm-Corporation/Cookbook. The code should save the QR code as an image file.
"""
# Example usage:
api_key = os.getenv("OPENAI_API_KEY")
# Model
model = OpenAIChat(
openai_api_key=api_key, model_name="gpt-4o-mini", temperature=0.1
)
# Initialize your agents for QR code generation
agents = [
Agent(
agent_name="QR-Code-Generator-Agent-Luma",
system_prompt=QR_CODE_AGENT_1_SYS_PROMPT,
llm=model,
model_name="gpt-4.1",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="qr_code_agent_luma.json",
@ -278,7 +259,7 @@ agents = [
Agent(
agent_name="QR-Code-Generator-Agent-Cookbook",
system_prompt=QR_CODE_AGENT_2_SYS_PROMPT,
llm=model,
model_name="gpt-4.1",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="qr_code_agent_cookbook.json",
@ -310,9 +291,7 @@ swarm.run(
```python
import os
from swarms import Agent
from swarm_models import OpenAIChat
from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm
from swarms import Agent, SpreadSheetSwarm
# Define custom system prompts for each social media platform
TWITTER_AGENT_SYS_PROMPT = """
@ -344,7 +323,7 @@ agents = [
Agent(
agent_name="Twitter-Marketing-Agent",
system_prompt=TWITTER_AGENT_SYS_PROMPT,
llm=model,
model_name="gpt-4.1",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="twitter_agent.json",
@ -354,7 +333,7 @@ agents = [
Agent(
agent_name="Instagram-Marketing-Agent",
system_prompt=INSTAGRAM_AGENT_SYS_PROMPT,
llm=model,
model_name="gpt-4.1",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="instagram_agent.json",
@ -364,7 +343,7 @@ agents = [
Agent(
agent_name="Facebook-Marketing-Agent",
system_prompt=FACEBOOK_AGENT_SYS_PROMPT,
llm=model,
model_name="gpt-4.1",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="facebook_agent.json",
@ -374,7 +353,7 @@ agents = [
Agent(
agent_name="Email-Marketing-Agent",
system_prompt=EMAIL_AGENT_SYS_PROMPT,
llm=model,
model_name="gpt-4.1",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="email_agent.json",
@ -404,22 +383,11 @@ swarm.run(
## Additional Information and Tips
- **Thread Synchronization**: When working with multiple agents in a concurrent environment, it's crucial to ensure that access to shared resources is properly synchronized using locks to avoid race conditions.
- **Autosave Feature**: If you enable the `autosave_on` flag, ensure that the file path provided is correct and writable. This feature is handy for long-running tasks where you want to periodically save the state.
- **Error Handling**
: Implementing proper error handling within your agents can prevent the swarm from crashing during execution. Consider catching exceptions in the `run` method and logging errors appropriately.
- **Custom Agents**: You can extend the `Agent` class to create custom agents that perform specific tasks tailored to your application's needs.
| Tip/Feature | Description |
|------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Thread Synchronization** | When working with multiple agents in a concurrent environment, it's crucial to ensure that access to shared resources is properly synchronized using locks to avoid race conditions. |
| **Autosave Feature** | If you enable the `autosave_on` flag, ensure that the file path provided is correct and writable. This feature is handy for long-running tasks where you want to periodically save the state. |
| **Error Handling** | Implementing proper error handling within your agents can prevent the swarm from crashing during execution. Consider catching exceptions in the `run` method and logging errors appropriately. |
| **Custom Agents** | You can extend the `Agent` class to create custom agents that perform specific tasks tailored to your application's needs. |
---
## References and Resources
- [Python's `queue` module](https://docs.python.org/3/library/queue.html)
- [Python's `threading` module](https://docs.python.org/3/library/threading.html)
- [CSV File Handling in Python](https://docs.python.org/3/library/csv.html)
- [JSON Handling in Python](https://docs.python.org/3/library/json.html)

@ -2,6 +2,8 @@
SwarmRearrange is a class for orchestrating multiple swarms in a sequential or parallel flow pattern. It provides thread-safe operations for managing swarm execution, history tracking, and flow validation.
Full Path: `from swarms.structs.swarm_rearrange import SwarmRearrange`
## Constructor Arguments
| Parameter | Type | Default | Description |
@ -38,7 +40,9 @@ Executes the swarm arrangement according to the flow pattern.
The flow pattern uses arrow notation (`->`) to define execution order:
- Sequential: `"SwarmA -> SwarmB -> SwarmC"`
- Parallel: `"SwarmA, SwarmB -> SwarmC"`
- Human intervention: Use `"H"` in the flow
## Examples
@ -46,25 +50,12 @@ The flow pattern uses arrow notation (`->`) to define execution order:
### Basic Sequential Flow
```python
from swarms.structs.swarm_rearrange import SwarmRearrange
import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange, SwarmRearrange
# model = Anthropic(anthropic_api_key=os.getenv("ANTHROPIC_API_KEY"))
company = "TGSC"
# 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(
@ -79,14 +70,8 @@ managing_director = Agent(
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,
model_name="gpt-4.1",
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
@ -103,14 +88,8 @@ vp_finance = Agent(
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,
model_name="gpt-4.1",
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
@ -127,14 +106,8 @@ industry_analyst = Agent(
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,
model_name="gpt-4.1",
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
@ -151,14 +124,8 @@ tech_expert = Agent(
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,
model_name="gpt-4.1",
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
@ -175,14 +142,9 @@ market_researcher = Agent(
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,
model_name="gpt-4.1",
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
@ -199,14 +161,8 @@ regulatory_specialist = Agent(
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,
model_name="gpt-4.1",
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
@ -284,51 +240,13 @@ arrangement = SwarmRearrange(
result = arrangement.run("Initial task")
```
### Complex Multi-Stage Pipeline
```python
# Define multiple flow patterns
flows = [
"Collector -> Processor -> Analyzer",
"Analyzer -> ML -> Validator",
"Validator -> Reporter"
]
# Create arrangements for each flow
pipelines = [
SwarmRearrange(name=f"Pipeline{i}", swarms=swarms, flow=flow)
for i, flow in enumerate(flows)
]
# Create master arrangement
master = SwarmRearrange(
name="MasterPipeline",
swarms=pipelines,
flow="Pipeline0 -> Pipeline1 -> Pipeline2"
)
# Execute complete pipeline
result = master.run("Start analysis")
```
## Best Practices
1. **Flow Validation**: Always validate flows before execution
2. **Error Handling**: Implement try-catch blocks around run() calls
3. **History Tracking**: Use track_history() for monitoring swarm execution
4. **Resource Management**: Set appropriate max_loops to prevent infinite execution
5. **Logging**: Enable verbose mode during development for detailed logging
## Error Handling
The class implements comprehensive error handling:
```python
try:
arrangement = SwarmRearrange(swarms=swarms, flow=flow)
result = arrangement.run(task)
except ValueError as e:
logger.error(f"Flow validation error: {e}")
except Exception as e:
logger.error(f"Execution error: {e}")
```
| Best Practice | Description |
|------------------------|-----------------------------------------------------------------------------------------------|
| **Flow Validation** | Always validate flows before execution |
| **Error Handling** | Implement try-catch blocks around `run()` calls |
| **History Tracking** | Use `track_history()` for monitoring swarm execution |
| **Resource Management**| Set appropriate `max_loops` to prevent infinite execution |
| **Logging** | Enable verbose mode during development for detailed logging |

@ -1,65 +1,11 @@
# SwarmRouter Documentation
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:
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.
| Swarm Type | Description |
|------------|-------------|
| `AgentRearrange` | Optimizes agent arrangement for task execution |
| `MixtureOfAgents` | Combines multiple agent types for diverse tasks |
| `SpreadSheetSwarm` | Uses spreadsheet-like operations for task management |
| `SequentialWorkflow` | Executes tasks sequentially |
| `ConcurrentWorkflow` | Executes tasks in parallel |
| `GroupChat` | Facilitates communication among agents in a group chat format |
| `MultiAgentRouter` | Routes tasks between multiple agents |
| `AutoSwarmBuilder` | Automatically builds swarm structure |
| `HiearchicalSwarm` | Hierarchical organization of agents |
| `MajorityVoting` | Uses majority voting for decision making |
| `MALT` | Multi-Agent Language Tasks |
| `CouncilAsAJudge` | Council-based judgment system |
| `InteractiveGroupChat` | Interactive group chat with user participation |
| `auto` | Automatically selects best swarm type via embedding search |
## Classes
### Document
A Pydantic model for representing document data.
| Attribute | Type | Description |
| --- | --- | --- |
| `file_path` | str | Path to the document file. |
| `data` | str | Content of the document. |
Full Path: `from swarms.structs.swarm_router`
### SwarmLog
A Pydantic model for capturing log entries.
| Attribute | Type | Description |
| --- | --- | --- |
| `id` | str | Unique identifier for the log entry. |
| `timestamp` | datetime | Time of log creation. |
| `level` | str | Log level (e.g., "info", "error"). |
| `message` | str | Log message content. |
| `swarm_type` | SwarmType | Type of swarm associated with the log. |
| `task` | str | Task being performed (optional). |
| `metadata` | Dict[str, Any] | Additional metadata (optional). |
| `documents` | List[Document] | List of documents associated with the log. |
### SwarmRouterConfig
Configuration model for SwarmRouter.
| Attribute | Type | Description |
| --- | --- | --- |
| `name` | str | Name identifier for the SwarmRouter instance |
| `description` | str | Description of the SwarmRouter's purpose |
| `swarm_type` | SwarmType | Type of swarm to use |
| `rearrange_flow` | Optional[str] | Flow configuration string |
| `rules` | Optional[str] | Rules to inject into every agent |
| `multi_agent_collab_prompt` | bool | Whether to enable multi-agent collaboration prompts |
| `task` | str | The task to be executed by the swarm |
### SwarmRouter
## Initialization Parameters
Main class for routing tasks to different swarm types.
@ -108,13 +54,28 @@ Main class for routing tasks to different swarm types.
| `concurrent_batch_run` | `tasks: List[str], *args, **kwargs` | Execute multiple tasks concurrently |
## Installation
## Available Swarm Types
The `SwarmRouter` supports many various multi-agent architectures for various applications.
| Swarm Type | Description |
|------------|-------------|
| `AgentRearrange` | Optimizes agent arrangement for task execution |
| `MixtureOfAgents` | Combines multiple agent types for diverse tasks |
| `SpreadSheetSwarm` | Uses spreadsheet-like operations for task management |
| `SequentialWorkflow` | Executes tasks sequentially |
| `ConcurrentWorkflow` | Executes tasks in parallel |
| `GroupChat` | Facilitates communication among agents in a group chat format |
| `MultiAgentRouter` | Routes tasks between multiple agents |
| `AutoSwarmBuilder` | Automatically builds swarm structure |
| `HiearchicalSwarm` | Hierarchical organization of agents |
| `MajorityVoting` | Uses majority voting for decision making |
| `MALT` | Multi-Agent Language Tasks |
| `CouncilAsAJudge` | Council-based judgment system |
| `InteractiveGroupChat` | Interactive group chat with user participation |
| `auto` | Automatically selects best swarm type via embedding search |
To use the SwarmRouter, first install the required dependencies:
```bash
pip install swarms swarm_models
```
## Basic Usage
@ -122,20 +83,6 @@ pip install swarms swarm_models
import os
from dotenv import load_dotenv
from swarms import Agent, SwarmRouter, SwarmType
from swarm_models import OpenAIChat
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:
@ -158,31 +105,15 @@ Deliver clear, concise summaries that capture the essence of various documents w
data_extractor_agent = Agent(
agent_name="Data-Extractor",
system_prompt=DATA_EXTRACTOR_PROMPT,
llm=model,
model_name="gpt-4.1",
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,
model_name="gpt-4.1",
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",
)
# Initialize the SwarmRouter
@ -192,8 +123,6 @@ router = SwarmRouter(
max_loops=1,
agents=[data_extractor_agent, summarizer_agent],
swarm_type="ConcurrentWorkflow",
autosave=True,
return_json=True,
)
# Example usage
@ -203,10 +132,6 @@ if __name__ == "__main__":
"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}")
```
## Advanced Usage
@ -243,40 +168,6 @@ auto_router = SwarmRouter(
result = auto_router.run("Analyze and summarize the quarterly financial report")
```
### Loading Agents from CSV
To load agents from a CSV file:
```python
csv_router = SwarmRouter(
name="CSVAgentRouter",
load_agents_from_csv=True,
csv_file_path="agents.csv",
swarm_type="SequentialWorkflow"
)
result = csv_router.run("Process the client data")
```
### Using Shared Memory System
To enable shared memory across agents:
```python
from swarms.memory import SemanticMemory
memory_system = SemanticMemory()
memory_router = SwarmRouter(
name="MemoryRouter",
agents=[agent1, agent2],
shared_memory_system=memory_system,
swarm_type="SequentialWorkflow"
)
result = memory_router.run("Analyze historical data and make predictions")
```
### Injecting Rules to All Agents
To inject common rules into all agents:
@ -454,6 +345,7 @@ result = voting_router.run("Should we invest in Company X based on the available
```
### Auto Select (Experimental)
Autonomously selects the right swarm by conducting vector search on your input task or name or description or all 3.
```python
@ -551,18 +443,3 @@ router = SwarmRouter(
result = router("Analyze the market data") # Equivalent to router.run("Analyze the market data")
```
### Using the swarm_router Function
For quick one-off tasks, you can use the swarm_router function:
```python
from swarms import swarm_router
result = swarm_router(
name="QuickRouter",
agents=[agent1, agent2],
swarm_type="ConcurrentWorkflow",
task="Analyze the quarterly report"
)
```

@ -1,66 +1,114 @@
# AgentLoader Documentation
The `AgentLoader` is a powerful utility for creating Swarms agents from markdown files using the Claude Code sub-agent format. It supports both single and multiple markdown file loading, providing a flexible way to define and deploy agents using YAML frontmatter configuration.
The `AgentLoader` is a comprehensive utility for creating Swarms agents from various file formats including Markdown, YAML, and CSV files. It provides a unified interface for loading agents with support for concurrent processing, configuration overrides, and automatic file type detection.
## Overview
The AgentLoader enables you to:
- Load single agents from markdown files with YAML frontmatter
- Load multiple agents from directories or file lists with concurrent processing
- Parse Claude Code sub-agent YAML frontmatter configurations
- Extract system prompts from markdown content
- Utilize 100% CPU cores for high-performance batch loading
- Provide comprehensive error handling and validation
- Load agents from Markdown files
- Load agents from YAML configuration files
- Load agents from CSV files
- Automatically detect file types and use appropriate loaders
- Process multiple files concurrently for improved performance
- Override default configurations with custom parameters
- Handle various agent configurations and settings
## Installation
The AgentLoader is included with the Swarms framework:
```python
from swarms import AgentLoader, load_agent_from_markdown, load_agents_from_markdown
from swarms.structs import AgentLoader
from swarms.utils import load_agent_from_markdown, load_agents_from_markdown
```
## Markdown Format
## Supported File Formats
The AgentLoader uses the Claude Code sub-agent YAML frontmatter format:
### 1. Markdown Files (Claude Code Format)
The primary format uses YAML frontmatter with markdown content:
```markdown
---
name: your-sub-agent-name
description: Description of when this subagent should be invoked
model_name: gpt-4
temperature: 0.3
max_loops: 2
name: FinanceAdvisor
description: Expert financial advisor for investment and budgeting guidance
model_name: claude-sonnet-4-20250514
temperature: 0.7
max_loops: 1
mcp_url: http://example.com/mcp # optional
---
Your subagent's system prompt goes here. This can be multiple paragraphs
and should clearly define the subagent's role, capabilities, and approach
to solving problems.
You are an expert financial advisor with deep knowledge in:
- Investment strategies and portfolio management
- Personal budgeting and financial planning
- Risk assessment and diversification
- Tax optimization strategies
- Retirement planning
Your approach:
- Provide clear, actionable financial advice
- Consider individual risk tolerance and goals
- Explain complex concepts in simple terms
- Always emphasize the importance of diversification
- Include relevant disclaimers about financial advice
Include specific instructions, best practices, and any constraints
the subagent should follow.
When analyzing financial situations:
1. Assess current financial position
2. Identify short-term and long-term goals
3. Evaluate risk tolerance
4. Recommend appropriate strategies
5. Suggest specific action steps
```
**Schema Fields:**
- `name` (required): Your sub-agent name
- `description` (required): Description of when this subagent should be invoked
- `model_name` (optional): Name of model (defaults to random selection if not provided)
- `temperature` (optional): Float value for model temperature (0.0-2.0)
- `max_loops` (optional): Integer for maximum reasoning loops
- `mcp_url` (optional): MCP server URL if needed
| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `name` | string | ✅ Yes | - | Your agent name |
| `description` | string | ✅ Yes | - | Description of the agent's role and capabilities |
| `model_name` | string | ❌ No | "gpt-4.1" | Name of the model to use |
| `temperature` | float | ❌ No | 0.1 | Model temperature (0.0-2.0) |
| `max_loops` | integer | ❌ No | 1 | Maximum reasoning loops |
| `mcp_url` | string | ❌ No | None | MCP server URL if needed |
| `streaming_on` | boolean | ❌ No | False | Enable streaming output |
### 2. YAML Files
YAML configuration files for agent definitions:
```yaml
agents:
- name: "ResearchAgent"
description: "Research and analysis specialist"
model_name: "gpt-4"
temperature: 0.3
max_loops: 2
system_prompt: "You are a research specialist..."
```
### 3. CSV Files
CSV files with agent configurations:
```csv
name,description,model_name,temperature,max_loops
ResearchAgent,Research specialist,gpt-4,0.3,2
AnalysisAgent,Data analyst,claude-3,0.1,1
```
## Quick Start
### Loading a Single Agent
```python
from swarms.utils import load_agent_from_markdown
from swarms.structs import AgentLoader
# Initialize the loader
loader = AgentLoader()
# Load agent from markdown file
agent = load_agent_from_markdown("finance_advisor.md")
agent = loader.load_agent_from_markdown("finance_advisor.md")
# Use the agent
response = agent.run(
@ -68,13 +116,15 @@ response = agent.run(
)
```
### Loading Multiple Agents (Concurrent)
### Loading Multiple Agents
```python
from swarms.utils import load_agents_from_markdown
from swarms.structs import AgentLoader
loader = AgentLoader()
# Load agents from list of files with concurrent processing
agents = load_agents_from_markdown([
agents = loader.load_agents_from_markdown([
"market_researcher.md",
"financial_analyst.md",
"risk_analyst.md"
@ -92,6 +142,19 @@ task = "Analyze the AI healthcare market for a $50M investment."
result = workflow.run(task)
```
### Automatic File Type Detection
```python
from swarms.structs import AgentLoader
loader = AgentLoader()
# Automatically detect file type and load appropriately
agents = loader.auto("agents.yaml") # YAML file
agents = loader.auto("agents.csv") # CSV file
agents = loader.auto("agents.md") # Markdown file
```
## Class-Based Usage
### AgentLoader Class
@ -99,7 +162,7 @@ result = workflow.run(task)
For more advanced usage, use the `AgentLoader` class directly:
```python
from swarms import AgentLoader
from swarms.structs import AgentLoader
# Initialize loader
loader = AgentLoader()
@ -111,7 +174,7 @@ agent = loader.load_single_agent("path/to/agent.md")
agents = loader.load_multiple_agents(
"./agents_directory/",
concurrent=True, # Enable concurrent processing
max_workers=8 # Optional: limit worker threads
max_file_size_mb=10.0 # Limit file size for memory safety
)
# Parse markdown file without creating agent
@ -124,35 +187,97 @@ print(config.name, config.description)
You can override default configuration when loading agents:
```python
agent = load_agent_from_markdown(
agent = loader.load_agent_from_markdown(
file_path="agent.md",
max_loops=5,
verbose=True,
dashboard=True,
autosave=False,
context_length=200000
context_length=200000,
temperature=0.5
)
```
### Available Configuration Parameters
- `max_loops` (int): Maximum number of reasoning loops (default: 1)
- `autosave` (bool): Enable automatic state saving (default: True)
- `dashboard` (bool): Enable dashboard monitoring (default: False)
- `verbose` (bool): Enable verbose logging (default: False)
- `dynamic_temperature_enabled` (bool): Enable dynamic temperature (default: False)
- `saved_state_path` (str): Path for saving agent state
- `user_name` (str): User identifier (default: "default_user")
- `retry_attempts` (int): Number of retry attempts (default: 3)
- `context_length` (int): Maximum context length (default: 100000)
- `return_step_meta` (bool): Return step metadata (default: False)
- `output_type` (str): Output format type (default: "str")
- `auto_generate_prompt` (bool): Auto-generate prompts (default: False)
- `artifacts_on` (bool): Enable artifacts (default: False)
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `max_loops` | int | 1 | Maximum number of reasoning loops |
| `autosave` | bool | False | Enable automatic state saving |
| `dashboard` | bool | False | Enable dashboard monitoring |
| `verbose` | bool | False | Enable verbose logging |
| `dynamic_temperature_enabled` | bool | False | Enable dynamic temperature |
| `saved_state_path` | str | None | Path for saving agent state |
| `user_name` | str | "default_user" | User identifier |
| `retry_attempts` | int | 3 | Number of retry attempts |
| `context_length` | int | 100000 | Maximum context length |
| `return_step_meta` | bool | False | Return step metadata |
| `output_type` | str | "str" | Output format type |
| `auto_generate_prompt` | bool | False | Auto-generate prompts |
| `streaming_on` | bool | False | Enable streaming output |
| `mcp_url` | str | None | MCP server URL if needed |
## Advanced Features
### Concurrent Processing
The AgentLoader utilizes multiple CPU cores for concurrent agent loading:
```python
from swarms.structs import AgentLoader
loader = AgentLoader()
# Automatic concurrent processing for multiple files
agents = loader.load_agents_from_markdown([
"agent1.md", "agent2.md", "agent3.md", "agent4.md"
]) # concurrent=True by default
# Manual control over concurrency
agents = loader.load_agents_from_markdown(
"./agents_directory/",
concurrent=True, # Enable concurrent processing
max_file_size_mb=5.0 # Limit file size for memory safety
)
# Disable concurrency for debugging or single files
agents = loader.load_agents_from_markdown(
["single_agent.md"],
concurrent=False # Sequential processing
)
```
### File Size Validation
## Complete Example
```python
# Set maximum file size to prevent memory issues
agents = loader.load_agents_from_markdown(
"./agents_directory/",
max_file_size_mb=5.0 # Skip files larger than 5MB
)
```
### Multiple File Type Support
```python
from swarms.structs import AgentLoader
loader = AgentLoader()
### Example: Finance Advisor Agent
# Load from different file types
yaml_agents = loader.load_agents_from_yaml("agents.yaml")
csv_agents = loader.load_agents_from_csv("agents.csv")
md_agents = loader.load_agents_from_markdown("agents.md")
# Load from multiple YAML files with different return types
yaml_files = ["agents1.yaml", "agents2.yaml"]
return_types = ["auto", "list"]
agents = loader.load_many_agents_from_yaml(yaml_files, return_types)
```
## Complete Examples
### Example 1: Finance Advisor Agent
Create a file `finance_advisor.md`:
@ -160,7 +285,7 @@ Create a file `finance_advisor.md`:
---
name: FinanceAdvisor
description: Expert financial advisor for investment and budgeting guidance
model_name: gpt-4
model_name: claude-sonnet-4-20250514
temperature: 0.7
max_loops: 1
---
@ -193,10 +318,11 @@ When analyzing financial situations:
### Loading and Using the Agent
```python
from swarms.utils import load_agent_from_markdown
from swarms.structs import AgentLoader
# Load the Finance Advisor agent
agent = load_agent_from_markdown("finance_advisor.md")
loader = AgentLoader()
agent = loader.load_agent_from_markdown("finance_advisor.md")
# Use the agent for financial advice
response = agent.run(
@ -204,128 +330,85 @@ response = agent.run(
)
```
## Error Handling
The AgentLoader provides comprehensive error handling:
### Example 2: Multi-Agent Workflow
```python
from swarms import AgentLoader
from swarms.structs import AgentLoader, SequentialWorkflow
# Load multiple specialized agents
loader = AgentLoader()
agents = loader.load_agents_from_markdown([
"market_researcher.md",
"financial_analyst.md",
"risk_analyst.md"
], concurrent=True)
try:
# This will raise FileNotFoundError
agent = loader.load_single_agent("nonexistent.md")
except FileNotFoundError as e:
print(f"File not found: {e}")
try:
# This will handle parsing errors gracefully
agents = loader.load_multiple_agents("./invalid_directory/")
print(f"Successfully loaded {len(agents)} agents")
except Exception as e:
print(f"Error loading agents: {e}")
```
## Concurrent Processing Features
### Multi-Core Performance
The AgentLoader utilizes 100% of CPU cores for concurrent agent loading, providing significant performance improvements when processing multiple markdown files:
```python
from swarms.utils import load_agents_from_markdown
# Automatic concurrent processing for multiple files
agents = load_agents_from_markdown([
"agent1.md", "agent2.md", "agent3.md", "agent4.md"
]) # concurrent=True by default
# Manual control over concurrency
agents = load_agents_from_markdown(
"./agents_directory/",
concurrent=True, # Enable concurrent processing
max_workers=8 # Limit to 8 worker threads
)
# Disable concurrency for debugging or single files
agents = load_agents_from_markdown(
["single_agent.md"],
concurrent=False # Sequential processing
# Create a sequential workflow
workflow = SequentialWorkflow(
agents=agents,
max_loops=1
)
```
### Resource Management
```python
# Default: Uses all CPU cores
agents = load_agents_from_markdown(files, concurrent=True)
# Custom worker count for resource control
agents = load_agents_from_markdown(
files,
concurrent=True,
max_workers=4 # Limit to 4 threads
)
# Execute complex task across multiple agents
task = """
Analyze the AI healthcare market for a $50M investment opportunity.
Focus on market size, competition, financials, and risks.
"""
# ThreadPoolExecutor automatically manages:
# - Thread lifecycle
# - Resource cleanup
# - Exception handling
# - Result collection
result = workflow.run(task)
```
## Advanced Features
### Custom System Prompt Building
The AgentLoader automatically builds comprehensive system prompts from the markdown structure:
### Example 3: Mixed File Types
```python
from swarms.structs import AgentLoader
loader = AgentLoader()
config = loader.parse_markdown_file("agent.md")
# The system prompt includes:
# - Role description from the table
# - Focus areas as bullet points
# - Approach as numbered steps
# - Expected outputs as deliverables
# Load agents from different file types
markdown_agents = loader.load_agents_from_markdown("./md_agents/")
yaml_agents = loader.load_agents_from_yaml("config.yaml")
csv_agents = loader.load_agents_from_csv("data.csv")
print("Generated System Prompt:")
print(config.system_prompt)
```
# Combine all agents
all_agents = markdown_agents + yaml_agents + csv_agents
print(f"Loaded {len(all_agents)} agents from various sources")
```
## Integration with Swarms
## Error Handling
The loaded agents are fully compatible with Swarms orchestration systems:
The AgentLoader provides comprehensive error handling:
```python
from swarms.utils import load_agents_from_markdown
from swarms.structs import SequentialWorkflow
from swarms.structs import AgentLoader
# Load multiple specialized agents
agents = load_agents_from_markdown("./specialist_agents/")
loader = AgentLoader()
# Create a sequential workflow
workflow = SequentialWorkflow(
agents=agents,
max_loops=1
)
try:
# This will raise FileNotFoundError
agent = loader.load_agent_from_markdown("nonexistent.md")
except FileNotFoundError as e:
print(f"File not found: {e}")
# Execute complex task across multiple agents
result = workflow.run("Conduct a comprehensive system audit")
try:
# This will handle parsing errors gracefully
agents = loader.load_multiple_agents("./invalid_directory/")
print(f"Successfully loaded {len(agents)} agents")
except Exception as e:
print(f"Error loading agents: {e}")
```
## Best Practices
1. **Consistent Naming**: Use clear, descriptive agent names
2. **Detailed Descriptions**: Provide comprehensive role descriptions
3. **Structured Sections**: Use the optional sections to define agent behavior
3. **Structured Content**: Use clear sections to define agent behavior
4. **Error Handling**: Always wrap agent loading in try-catch blocks
5. **Model Selection**: Choose appropriate models based on agent complexity
6. **Configuration**: Override defaults when specific behavior is needed
7. **File Organization**: Organize agents by domain or function
8. **Memory Management**: Use `max_file_size_mb` for large agent collections
## API Reference
@ -333,57 +416,243 @@ result = workflow.run("Conduct a comprehensive system audit")
```python
class AgentLoader:
def __init__(self, model: Optional[LiteLLM] = None)
def parse_markdown_file(self, file_path: str) -> MarkdownAgentConfig
def load_single_agent(self, file_path: str, **kwargs) -> Agent
def load_multiple_agents(self, file_paths: Union[str, List[str]], **kwargs) -> List[Agent]
"""
Loader class for creating Agent objects from various file formats.
This class provides methods to load agents from Markdown, YAML, and CSV files.
"""
def __init__(self):
"""Initialize the AgentLoader instance."""
pass
def load_agents_from_markdown(
self,
file_paths: Union[str, List[str]],
concurrent: bool = True,
max_file_size_mb: float = 10.0,
**kwargs
) -> List[Agent]:
"""
Load multiple agents from one or more Markdown files.
Args:
file_paths: Path or list of paths to Markdown file(s)
concurrent: Whether to load files concurrently
max_file_size_mb: Maximum file size in MB to process
**kwargs: Additional keyword arguments passed to the underlying loader
Returns:
A list of loaded Agent objects
"""
def load_agent_from_markdown(
self,
file_path: str,
**kwargs
) -> Agent:
"""
Load a single agent from a Markdown file.
Args:
file_path: Path to the Markdown file containing the agent definition
**kwargs: Additional keyword arguments passed to the underlying loader
Returns:
The loaded Agent object
"""
def load_agents_from_yaml(
self,
yaml_file: str,
return_type: ReturnTypes = "auto",
**kwargs
) -> List[Agent]:
"""
Load agents from a YAML file.
Args:
yaml_file: Path to the YAML file containing agent definitions
return_type: The return type for the loader
**kwargs: Additional keyword arguments passed to the underlying loader
Returns:
A list of loaded Agent objects
"""
def load_agents_from_csv(
self,
csv_file: str,
**kwargs
) -> List[Agent]:
"""
Load agents from a CSV file.
Args:
csv_file: Path to the CSV file containing agent definitions
**kwargs: Additional keyword arguments passed to the underlying loader
Returns:
A list of loaded Agent objects
"""
def auto(
self,
file_path: str,
*args,
**kwargs
):
"""
Automatically load agents from a file based on its extension.
Args:
file_path: Path to the agent file (Markdown, YAML, or CSV)
*args: Additional positional arguments passed to the underlying loader
**kwargs: Additional keyword arguments passed to the underlying loader
Returns:
A list of loaded Agent objects
Raises:
ValueError: If the file type is not supported
"""
```
**Method Parameters and Return Types:**
| Method | Parameters | Type | Required | Default | Return Type | Description |
|--------|------------|------|----------|---------|-------------|-------------|
| `load_agents_from_markdown` | `file_paths` | Union[str, List[str]] | ✅ Yes | - | List[Agent] | File path(s) or directory |
| `load_agents_from_markdown` | `concurrent` | bool | ❌ No | True | List[Agent] | Enable concurrent processing |
| `load_agents_from_markdown` | `max_file_size_mb` | float | ❌ No | 10.0 | List[Agent] | Max file size in MB |
| `load_agents_from_markdown` | `**kwargs` | dict | ❌ No | {} | List[Agent] | Configuration overrides |
| `load_agent_from_markdown` | `file_path` | str | ✅ Yes | - | Agent | Path to markdown file |
| `load_agent_from_markdown` | `**kwargs` | dict | ❌ No | {} | Agent | Configuration overrides |
| `load_agents_from_yaml` | `yaml_file` | str | ✅ Yes | - | List[Agent] | Path to YAML file |
| `load_agents_from_yaml` | `return_type` | ReturnTypes | ❌ No | "auto" | List[Agent] | Return type for loader |
| `load_agents_from_yaml` | `**kwargs` | dict | ❌ No | {} | List[Agent] | Configuration overrides |
| `load_agents_from_csv` | `csv_file` | str | ✅ Yes | - | List[Agent] | Path to CSV file |
| `load_agents_from_csv` | `**kwargs` | dict | ❌ No | {} | List[Agent] | Configuration overrides |
| `auto` | `file_path` | str | ✅ Yes | - | List[Agent] | Path to agent file |
| `auto` | `*args` | tuple | ❌ No | () | List[Agent] | Positional arguments |
| `auto` | `**kwargs` | dict | ❌ No | {} | List[Agent] | Keyword arguments |
### Convenience Functions
```python
def load_agent_from_markdown(file_path: str, **kwargs) -> Agent
def load_agent_from_markdown(
file_path: str,
**kwargs
) -> Agent:
"""
Load a single agent from a markdown file using the Claude Code YAML frontmatter format.
Args:
file_path: Path to the markdown file containing YAML frontmatter
**kwargs: Optional keyword arguments to override agent configuration
Returns:
Configured Agent instance loaded from the markdown file
"""
def load_agents_from_markdown(
file_paths: Union[str, List[str]],
concurrent: bool = True, # Enable concurrent processing
max_workers: Optional[int] = None, # Max worker threads (defaults to CPU count)
file_paths: Union[str, List[str]],
concurrent: bool = True,
max_file_size_mb: float = 10.0,
**kwargs
) -> List[Agent]
) -> List[Agent]:
"""
Load multiple agents from markdown files using the Claude Code YAML frontmatter format.
Args:
file_paths: Either a directory path containing markdown files or a list of markdown file paths
concurrent: If True, enables concurrent processing for faster loading
max_file_size_mb: Maximum file size (in MB) for each markdown file
**kwargs: Optional keyword arguments to override agent configuration
Returns:
List of configured Agent instances loaded from the markdown files
"""
```
**Function Parameters:**
| Function | Parameter | Type | Required | Default | Description |
|----------|-----------|------|----------|---------|-------------|
| `load_agent_from_markdown` | `file_path` | str | ✅ Yes | - | Path to markdown file |
| `load_agent_from_markdown` | `**kwargs` | dict | ❌ No | {} | Configuration overrides |
| `load_agents_from_markdown` | `file_paths` | Union[str, List[str]] | ✅ Yes | - | File path(s) or directory |
| `load_agents_from_markdown` | `concurrent` | bool | ❌ No | True | Enable concurrent processing |
| `load_agents_from_markdown` | `max_file_size_mb` | float | ❌ No | 10.0 | Max file size in MB |
| `load_agents_from_markdown` | `**kwargs` | dict | ❌ No | {} | Configuration overrides |
### Configuration Model
```python
class MarkdownAgentConfig(BaseModel):
name: str
description: str
model_name: Optional[str] = "gpt-4"
temperature: Optional[float] = 0.1 # Model temperature (0.0-2.0)
mcp_url: Optional[str] = None # Optional MCP server URL
system_prompt: str
max_loops: int = 1
autosave: bool = False
dashboard: bool = False
verbose: bool = False
# ... additional configuration fields
"""Configuration model for agents loaded from Claude Code markdown files."""
name: Optional[str] = None
description: Optional[str] = None
model_name: Optional[str] = "gpt-4.1"
temperature: Optional[float] = Field(default=0.1, ge=0.0, le=2.0)
mcp_url: Optional[int] = None
system_prompt: Optional[str] = None
max_loops: Optional[int] = Field(default=1, ge=1)
autosave: Optional[bool] = False
dashboard: Optional[bool] = False
verbose: Optional[bool] = False
dynamic_temperature_enabled: Optional[bool] = False
saved_state_path: Optional[str] = None
user_name: Optional[str] = "default_user"
retry_attempts: Optional[int] = Field(default=3, ge=1)
context_length: Optional[int] = Field(default=100000, ge=1000)
return_step_meta: Optional[bool] = False
output_type: Optional[str] = "str"
auto_generate_prompt: Optional[bool] = False
streaming_on: Optional[bool] = False
```
**MarkdownAgentConfig Schema:**
| Field | Type | Required | Default | Validation | Description |
|-------|------|----------|---------|------------|-------------|
| `name` | Optional[str] | ❌ No | None | - | Agent name |
| `description` | Optional[str] | ❌ No | None | - | Agent description |
| `model_name` | Optional[str] | ❌ No | "gpt-4.1" | - | Model to use |
| `temperature` | Optional[float] | ❌ No | 0.1 | 0.0 ≤ x ≤ 2.0 | Model temperature |
| `mcp_url` | Optional[int] | ❌ No | None | - | MCP server URL |
| `system_prompt` | Optional[str] | ❌ No | None | Non-empty string | System prompt |
| `max_loops` | Optional[int] | ❌ No | 1 | ≥ 1 | Maximum reasoning loops |
| `autosave` | Optional[bool] | ❌ No | False | - | Enable auto-save |
| `dashboard` | Optional[bool] | ❌ No | False | - | Enable dashboard |
| `verbose` | Optional[bool] | ❌ No | False | - | Enable verbose logging |
| `dynamic_temperature_enabled` | Optional[bool] | ❌ No | False | - | Enable dynamic temperature |
| `saved_state_path` | Optional[str] | ❌ No | None | - | State save path |
| `user_name` | Optional[str] | ❌ No | "default_user" | - | User identifier |
| `retry_attempts` | Optional[int] | ❌ No | 3 | ≥ 1 | Retry attempts |
| `context_length` | Optional[int] | ❌ No | 100000 | ≥ 1000 | Context length |
| `return_step_meta` | Optional[bool] | ❌ No | False | - | Return step metadata |
| `output_type` | Optional[str] | ❌ No | "str" | - | Output format |
| `auto_generate_prompt` | Optional[bool] | ❌ No | False | - | Auto-generate prompts |
| `streaming_on` | Optional[bool] | ❌ No | False | - | Enable streaming |
## Examples Repository
Find complete working examples in the `examples/agent_loader/` directory:
Find complete working examples in the `examples/utils/agent_loader/` directory:
### Single Agent Example (`agent_loader_demo.py`)
```python
from swarms.utils import load_agent_from_markdown
agent = load_agent_from_markdown("finance_advisor.md")
agent.run(
task="Analyze the financial market trends for 2023."
)
agent.run(task="What were the best performing etfs in 2023")
```
### Multi-Agent Workflow Example (`multi_agents_loader_demo.py`)
```python
from swarms.utils import load_agents_from_markdown
@ -410,11 +679,12 @@ result = workflow.run(task)
```
### Sample Agent Definition (`finance_advisor.md`)
```markdown
---
name: FinanceAdvisor
description: Expert financial advisor for investment and budgeting guidance
model_name: gpt-4o
model_name: claude-sonnet-4-20250514
temperature: 0.7
max_loops: 1
---
@ -444,6 +714,67 @@ When analyzing financial situations:
5. Suggest specific action steps
```
## Performance Considerations
### Concurrent Processing
- **Default Behavior**: Uses `os.cpu_count() * 2` worker threads
- **Memory Management**: Automatically validates file sizes before processing
- **Timeout Handling**: 5-minute total timeout, 1-minute per agent timeout
- **Error Recovery**: Continues processing other files if individual files fail
### File Size Limits
- **Default Limit**: 10MB maximum file size
- **Configurable**: Adjustable via `max_file_size_mb` parameter
- **Memory Safety**: Prevents memory issues with large agent definitions
### Resource Optimization
```python
# For large numbers of agents, consider batch processing
loader = AgentLoader()
# Process in smaller batches
batch1 = loader.load_agents_from_markdown("./batch1/", concurrent=True)
batch2 = loader.load_agents_from_markdown("./batch2/", concurrent=True)
# Or limit concurrent workers for resource-constrained environments
agents = loader.load_agents_from_markdown(
"./agents/",
concurrent=True,
max_file_size_mb=5.0 # Smaller files for faster processing
)
```
## Troubleshooting
### Common Issues
1. **File Not Found**: Ensure file paths are correct and files exist
2. **YAML Parsing Errors**: Check YAML frontmatter syntax in markdown files
3. **Memory Issues**: Reduce `max_file_size_mb` or process files in smaller batches
4. **Timeout Errors**: Check file sizes and network connectivity for remote files
5. **Configuration Errors**: Verify all required fields are present in agent definitions
### Debug Mode
```python
import logging
from swarms.structs import AgentLoader
# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
loader = AgentLoader()
# Load with verbose output
agent = loader.load_agent_from_markdown(
"agent.md",
verbose=True
)
```
## Support
For questions and support:

@ -0,0 +1,23 @@
# Swarms API Documentation Has Moved 🚀
We are excited to announce that the documentation for the Swarms API has been migrated to a brand new platform: [docs.swarms.ai](https://docs.swarms.ai).
Our new documentation site offers a more beautiful, user-friendly, and streamlined experience for developers and users alike. Youll find improved navigation, clearer guides, and up-to-date references for all Swarms Cloud API features.
**Whats new at [docs.swarms.ai](https://docs.swarms.ai)?**
- Modern, easy-to-navigate interface
- Comprehensive API reference and usage examples
- Quickstart guides and best practices
- Regular updates and new content
- Enhanced search and accessibility
If you have previously bookmarked or referenced the old documentation, please update your links to point to the new site. All future updates, new features, and support resources will be available exclusively at [docs.swarms.ai](https://docs.swarms.ai).
Thank you for being part of the Swarms community! If you have any questions or feedback about the new documentation, feel free to reach out via our [Discord](https://discord.gg/EamjgSaEQf) or [GitHub](https://github.com/kyegomez/swarms).
Happy building with Swarms!

@ -0,0 +1,11 @@
from swarms import Agent
from swarms_tools import exa_search
agent = Agent(
name="Exa Search Agent",
llm="gpt-4o-mini",
tools=[exa_search],
)
agent.run("What are the latest experimental treatments for diabetes?")

@ -1,4 +1,5 @@
from swarms import Agent
from swarms_tools import exa_search
# Initialize the agent
agent = Agent(
@ -8,7 +9,8 @@ agent = Agent(
dynamic_temperature_enabled=True,
max_loops=1,
dynamic_context_window=True,
streaming_on=True,
tools=[exa_search],
streaming_on=False,
)
out = agent.run(

@ -1,6 +1,3 @@
import os
from swarm_models import OpenAIChat
from swarms import Agent
from fluid_api_agent.main import fluid_api_request
from dotenv import load_dotenv
@ -8,17 +5,6 @@ from dotenv import load_dotenv
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,
)
def omni_api(task: str) -> str:
"""
@ -98,22 +84,11 @@ agent = Agent(
agent_name="API-Finance-Expert",
agent_description="An API expert agent specialized in financial analysis and investment planning.",
system_prompt=API_AGENT_SYS_PROMPT,
max_loops=1, # Allow a few iterations for refining outputs
llm=model,
dynamic_temperature_enabled=True, # Enable temperature adjustments for optimal creativity
user_name="swarms_corp",
retry_attempts=5, # Retry API calls to ensure reliability
context_length=8192, # Context length for comprehensive analysis
return_step_meta=False,
output_type="str", # Output tables or results in markdown format
auto_generate_prompt=False, # Use the custom system prompt for guidance
max_tokens=4000,
saved_state_path="api_finance_expert.json",
tools=[omni_api], # Integrate the omni_api tool
model_name="gpt-4o-mini",
tools=[omni_api],
)
# Run the agent with a financial task
agent.run(
"Fetch the current price for eth",
all_cores=True, # Utilize all processing cores for efficiency
"Fetch the current price for eth with coingecko",
)

@ -1,311 +0,0 @@
import torch
from torch import Tensor
from loguru import logger
from typing import Tuple
import matplotlib.pyplot as plt
try:
# ipywidgets is available in interactive environments like Jupyter.
from ipywidgets import interact, IntSlider
HAS_IPYWIDGETS = True
except ImportError:
HAS_IPYWIDGETS = False
logger.warning(
"ipywidgets not installed. Interactive slicing will be disabled."
)
class GaussianSplat4DStateSpace:
"""
4D Gaussian splatting with a state space model in PyTorch.
Each Gaussian is defined by an 8D state vector:
[x, y, z, w, vx, vy, vz, vw],
where the first four dimensions are the spatial coordinates and the last
four are the velocities. Only the spatial (first four) dimensions are used
for the 4D Gaussian splat, with a corresponding 4×4 covariance matrix.
Attributes:
num_gaussians (int): Number of Gaussians.
state_dim (int): Dimension of the state vector (should be 8).
states (Tensor): Current state for each Gaussian of shape (num_gaussians, state_dim).
covariances (Tensor): Covariance matrices for the spatial dimensions, shape (num_gaussians, 4, 4).
A (Tensor): State transition matrix of shape (state_dim, state_dim).
dt (float): Time step for state updates.
"""
def __init__(
self,
num_gaussians: int,
init_states: Tensor,
init_covariances: Tensor,
dt: float = 1.0,
) -> None:
"""
Initialize the 4D Gaussian splat model.
Args:
num_gaussians (int): Number of Gaussians.
init_states (Tensor): Initial states of shape (num_gaussians, 8).
Each state is assumed to be
[x, y, z, w, vx, vy, vz, vw].
init_covariances (Tensor): Initial covariance matrices for the spatial dimensions,
shape (num_gaussians, 4, 4).
dt (float): Time step for the state update.
"""
if init_states.shape[1] != 8:
raise ValueError(
"init_states should have shape (N, 8) where 8 = 4 position + 4 velocity."
)
if init_covariances.shape[1:] != (4, 4):
raise ValueError(
"init_covariances should have shape (N, 4, 4)."
)
self.num_gaussians = num_gaussians
self.states = init_states.clone() # shape: (N, 8)
self.covariances = (
init_covariances.clone()
) # shape: (N, 4, 4)
self.dt = dt
self.state_dim = init_states.shape[1]
# Create an 8x8 constant-velocity state transition matrix:
# New position = position + velocity*dt, velocity remains unchanged.
I4 = torch.eye(
4, dtype=init_states.dtype, device=init_states.device
)
zeros4 = torch.zeros(
(4, 4), dtype=init_states.dtype, device=init_states.device
)
top = torch.cat([I4, dt * I4], dim=1)
bottom = torch.cat([zeros4, I4], dim=1)
self.A = torch.cat([top, bottom], dim=0) # shape: (8, 8)
logger.info(
"Initialized 4D GaussianSplatStateSpace with {} Gaussians.",
num_gaussians,
)
def update_states(self) -> None:
"""
Update the state of each Gaussian using the constant-velocity state space model.
Applies:
state_next = A @ state_current.
"""
self.states = (
self.A @ self.states.t()
).t() # shape: (num_gaussians, 8)
logger.debug("States updated: {}", self.states)
def _compute_gaussian(
self, pos: Tensor, cov: Tensor, coords: Tensor
) -> Tensor:
"""
Compute the 4D Gaussian function over a grid of coordinates.
Args:
pos (Tensor): The center of the Gaussian (4,).
cov (Tensor): The 4×4 covariance matrix.
coords (Tensor): A grid of coordinates of shape (..., 4).
Returns:
Tensor: Evaluated Gaussian values on the grid with shape equal to coords.shape[:-1].
"""
try:
cov_inv = torch.linalg.inv(cov)
except RuntimeError as e:
logger.warning(
"Covariance inversion failed; using pseudo-inverse. Error: {}",
e,
)
cov_inv = torch.linalg.pinv(cov)
# Broadcast pos over the grid
diff = coords - pos.view(
*(1 for _ in range(coords.ndim - 1)), 4
)
mahal = torch.einsum("...i,ij,...j->...", diff, cov_inv, diff)
gaussian = torch.exp(-0.5 * mahal)
return gaussian
def render(
self,
canvas_size: Tuple[int, int, int, int],
sigma_scale: float = 1.0,
normalize: bool = False,
) -> Tensor:
"""
Render the current 4D Gaussian splats onto a 4D canvas.
Args:
canvas_size (Tuple[int, int, int, int]): The size of the canvas (d1, d2, d3, d4).
sigma_scale (float): Scaling factor for the covariance (affects spread).
normalize (bool): Whether to normalize the final canvas to [0, 1].
Returns:
Tensor: A 4D tensor (canvas) with the accumulated contributions from all Gaussians.
"""
d1, d2, d3, d4 = canvas_size
# Create coordinate grids for each dimension.
grid1 = torch.linspace(
0, d1 - 1, d1, device=self.states.device
)
grid2 = torch.linspace(
0, d2 - 1, d2, device=self.states.device
)
grid3 = torch.linspace(
0, d3 - 1, d3, device=self.states.device
)
grid4 = torch.linspace(
0, d4 - 1, d4, device=self.states.device
)
# Create a 4D meshgrid (using indexing "ij")
grid = torch.stack(
torch.meshgrid(grid1, grid2, grid3, grid4, indexing="ij"),
dim=-1,
) # shape: (d1, d2, d3, d4, 4)
# Initialize the canvas.
canvas = torch.zeros(
(d1, d2, d3, d4),
dtype=self.states.dtype,
device=self.states.device,
)
for i in range(self.num_gaussians):
pos = self.states[i, :4] # spatial center (4,)
cov = (
self.covariances[i] * sigma_scale
) # scaled covariance
gaussian = self._compute_gaussian(pos, cov, grid)
canvas += gaussian
logger.debug(
"Rendered Gaussian {} at position {}", i, pos.tolist()
)
if normalize:
max_val = canvas.max()
if max_val > 0:
canvas = canvas / max_val
logger.debug("Canvas normalized.")
logger.info("4D Rendering complete.")
return canvas
def interactive_slice(canvas: Tensor) -> None:
"""
Display an interactive 2D slice of the 4D canvas using ipywidgets.
This function fixes two of the four dimensions (d3 and d4) via sliders and
displays the resulting 2D slice (over dimensions d1 and d2).
Args:
canvas (Tensor): A 4D tensor with shape (d1, d2, d3, d4).
"""
d1, d2, d3, d4 = canvas.shape
def display_slice(slice_d3: int, slice_d4: int):
slice_2d = canvas[:, :, slice_d3, slice_d4].cpu().numpy()
plt.figure(figsize=(6, 6))
plt.imshow(slice_2d, cmap="hot", origin="lower")
plt.title(f"2D Slice at d3={slice_d3}, d4={slice_d4}")
plt.colorbar()
plt.show()
interact(
display_slice,
slice_d3=IntSlider(min=0, max=d3 - 1, step=1, value=d3 // 2),
slice_d4=IntSlider(min=0, max=d4 - 1, step=1, value=d4 // 2),
)
def mip_projection(canvas: Tensor) -> None:
"""
Render a 2D view of the 4D canvas using maximum intensity projection (MIP)
along the 3rd and 4th dimensions.
Args:
canvas (Tensor): A 4D tensor with shape (d1, d2, d3, d4).
"""
# MIP along dimension 3
mip_3d = canvas.max(dim=2)[0] # shape: (d1, d2, d4)
# MIP along dimension 4
mip_2d = mip_3d.max(dim=2)[0] # shape: (d1, d2)
plt.figure(figsize=(6, 6))
plt.imshow(mip_2d.cpu().numpy(), cmap="hot", origin="lower")
plt.title("2D MIP (Projecting dimensions d3 and d4)")
plt.colorbar()
plt.show()
def main() -> None:
"""
Main function that:
- Creates a 4D Gaussian splat model.
- Updates the states to simulate motion.
- Renders a 4D canvas.
- Visualizes the 4D volume via interactive slicing (if available) or MIP.
"""
torch.manual_seed(42)
num_gaussians = 2
# Define initial states for each Gaussian:
# Each state is [x, y, z, w, vx, vy, vz, vw].
init_states = torch.tensor(
[
[10.0, 15.0, 20.0, 25.0, 0.5, -0.2, 0.3, 0.1],
[30.0, 35.0, 40.0, 45.0, -0.3, 0.4, -0.1, 0.2],
],
dtype=torch.float32,
)
# Define initial 4x4 covariance matrices for the spatial dimensions.
init_covariances = torch.stack(
[
torch.diag(
torch.tensor(
[5.0, 5.0, 5.0, 5.0], dtype=torch.float32
)
),
torch.diag(
torch.tensor(
[3.0, 3.0, 3.0, 3.0], dtype=torch.float32
)
),
]
)
# Create the 4D Gaussian splat model.
model = GaussianSplat4DStateSpace(
num_gaussians, init_states, init_covariances, dt=1.0
)
# Update states to simulate one time step.
model.update_states()
# Render the 4D canvas.
canvas_size = (20, 20, 20, 20)
canvas = model.render(
canvas_size, sigma_scale=1.0, normalize=True
)
# Visualize the 4D data.
if HAS_IPYWIDGETS:
logger.info("Launching interactive slicing tool for 4D data.")
interactive_slice(canvas)
else:
logger.info(
"ipywidgets not available; using maximum intensity projection instead."
)
mip_projection(canvas)
if __name__ == "__main__":
main()

@ -1,42 +0,0 @@
import asyncio
from browser_use import Agent
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from swarms import ConcurrentWorkflow
load_dotenv()
class BrowserAgent:
def __init__(self, agent_name: str = "BrowserAgent"):
self.agent_name = agent_name
async def browser_agent_test(self, task: str):
agent = Agent(
task=task,
llm=ChatOpenAI(model="gpt-4o"),
)
result = await agent.run()
return result
def run(self, task: str):
return asyncio.run(self.browser_agent_test(task))
swarm = ConcurrentWorkflow(
agents=[BrowserAgent() for _ in range(10)],
)
swarm.run(
"""Please navigate to chat.com and engage in a detailed technical discussion with ChatGPT about the following specific aspects of future high-energy physics:
1. The potential discoveries and physics reach of the Future Circular Collider (FCC) compared to the LHC
2. Theoretical predictions for supersymmetric particles and dark matter candidates at energy scales above 100 TeV
3. Novel detector technologies needed for future collider experiments, particularly for tracking and calorimetry
4. The role of machine learning and quantum computing in analyzing high-energy physics data
5. Challenges and proposed solutions for beam focusing and acceleration at extremely high energies
Please document the key insights and technical details from this discussion."""
)

@ -1,46 +0,0 @@
from swarms.utils.vllm_wrapper import VLLMWrapper
def main():
# Initialize the vLLM wrapper with a model
# Note: You'll need to have the model downloaded or specify a HuggingFace model ID
llm = VLLMWrapper(
model_name="meta-llama/Llama-2-7b-chat-hf", # Replace with your model path or HF model ID
temperature=0.7,
max_tokens=1000,
)
# Example task
task = "What are the benefits of using vLLM for inference?"
# Run inference
response = llm.run(task)
print("Response:", response)
# Example with system prompt
llm_with_system = VLLMWrapper(
model_name="meta-llama/Llama-2-7b-chat-hf", # Replace with your model path or HF model ID
system_prompt="You are a helpful AI assistant that provides concise answers.",
temperature=0.7,
)
# Run inference with system prompt
response = llm_with_system.run(task)
print("\nResponse with system prompt:", response)
# Example with batched inference
tasks = [
"What is vLLM?",
"How does vLLM improve inference speed?",
"What are the main features of vLLM?",
]
responses = llm.batched_run(tasks, batch_size=2)
print("\nBatched responses:")
for task, response in zip(tasks, responses):
print(f"\nTask: {task}")
print(f"Response: {response}")
if __name__ == "__main__":
main()

@ -1,148 +0,0 @@
import concurrent.futures
import os
from typing import Any
from loguru import logger
try:
from vllm import LLM, SamplingParams
except ImportError:
import subprocess
import sys
print("Installing vllm")
subprocess.check_call(
[sys.executable, "-m", "pip", "install", "-U", "vllm"]
)
print("vllm installed")
from vllm import LLM, SamplingParams
class VLLMWrapper:
"""
A wrapper class for vLLM that provides a similar interface to LiteLLM.
This class handles model initialization and inference using vLLM.
"""
def __init__(
self,
model_name: str = "meta-llama/Llama-2-7b-chat-hf",
system_prompt: str | None = None,
stream: bool = False,
temperature: float = 0.5,
max_tokens: int = 4000,
max_completion_tokens: int = 4000,
tools_list_dictionary: list[dict[str, Any]] | None = None,
tool_choice: str = "auto",
parallel_tool_calls: bool = False,
*args,
**kwargs,
):
"""
Initialize the vLLM wrapper with the given parameters.
Args:
model_name (str): The name of the model to use. Defaults to "meta-llama/Llama-2-7b-chat-hf".
system_prompt (str, optional): The system prompt to use. Defaults to None.
stream (bool): Whether to stream the output. Defaults to False.
temperature (float): The temperature for sampling. Defaults to 0.5.
max_tokens (int): The maximum number of tokens to generate. Defaults to 4000.
max_completion_tokens (int): The maximum number of completion tokens. Defaults to 4000.
tools_list_dictionary (List[Dict[str, Any]], optional): List of available tools. Defaults to None.
tool_choice (str): How to choose tools. Defaults to "auto".
parallel_tool_calls (bool): Whether to allow parallel tool calls. Defaults to False.
"""
self.model_name = model_name
self.system_prompt = system_prompt
self.stream = stream
self.temperature = temperature
self.max_tokens = max_tokens
self.max_completion_tokens = max_completion_tokens
self.tools_list_dictionary = tools_list_dictionary
self.tool_choice = tool_choice
self.parallel_tool_calls = parallel_tool_calls
# Initialize vLLM
self.llm = LLM(model=model_name, **kwargs)
self.sampling_params = SamplingParams(
temperature=temperature,
max_tokens=max_tokens,
)
def _prepare_prompt(self, task: str) -> str:
"""
Prepare the prompt for the given task.
Args:
task (str): The task to prepare the prompt for.
Returns:
str: The prepared prompt.
"""
if self.system_prompt:
return f"{self.system_prompt}\n\nUser: {task}\nAssistant:"
return f"User: {task}\nAssistant:"
def run(self, task: str, *args, **kwargs) -> str:
"""
Run the model for the given task.
Args:
task (str): The task to run the model for.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
Returns:
str: The model's response.
"""
try:
prompt = self._prepare_prompt(task)
outputs = self.llm.generate(prompt, self.sampling_params)
response = outputs[0].outputs[0].text.strip()
return response
except Exception as error:
logger.error(f"Error in VLLMWrapper: {error}")
raise error
def __call__(self, task: str, *args, **kwargs) -> str:
"""
Call the model for the given task.
Args:
task (str): The task to run the model for.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
Returns:
str: The model's response.
"""
return self.run(task, *args, **kwargs)
def batched_run(
self, tasks: list[str], batch_size: int = 10
) -> list[str]:
"""
Run the model for multiple tasks in batches.
Args:
tasks (List[str]): List of tasks to run.
batch_size (int): Size of each batch. Defaults to 10.
Returns:
List[str]: List of model responses.
"""
# Calculate the worker count based on 95% of available CPU cores
num_workers = max(1, int((os.cpu_count() or 1) * 0.95))
with concurrent.futures.ThreadPoolExecutor(
max_workers=num_workers
) as executor:
futures = [
executor.submit(self.run, task) for task in tasks
]
return [
future.result()
for future in concurrent.futures.as_completed(futures)
]

@ -1,114 +0,0 @@
import os
from dotenv import load_dotenv
# Swarm imports
from swarms.structs.agent import Agent
from swarms.structs.hiearchical_swarm import (
HierarchicalSwarm,
SwarmSpec,
OrganizationalUnit,
)
from swarms.utils.function_caller_model import OpenAIFunctionCaller
# Load environment variables
load_dotenv()
# Create the agents first
research_manager = Agent(
agent_name="Research Manager",
agent_description="Manages research operations and coordinates research tasks",
system_prompt="You are a research manager responsible for overseeing research projects and coordinating research efforts.",
model_name="gpt-4o",
)
data_analyst = Agent(
agent_name="Data Analyst",
agent_description="Analyzes data and generates insights",
system_prompt="You are a data analyst specializing in processing and analyzing data to extract meaningful insights.",
model_name="gpt-4o",
)
research_assistant = Agent(
agent_name="Research Assistant",
agent_description="Assists with research tasks and data collection",
system_prompt="You are a research assistant who helps gather information and support research activities.",
model_name="gpt-4o",
)
development_manager = Agent(
agent_name="Development Manager",
agent_description="Manages development projects and coordinates development tasks",
system_prompt="You are a development manager responsible for overseeing software development projects and coordinating development efforts.",
model_name="gpt-4o",
)
software_engineer = Agent(
agent_name="Software Engineer",
agent_description="Develops and implements software solutions",
system_prompt="You are a software engineer specializing in building and implementing software solutions.",
model_name="gpt-4o",
)
qa_engineer = Agent(
agent_name="QA Engineer",
agent_description="Tests and ensures quality of software",
system_prompt="You are a QA engineer responsible for testing software and ensuring its quality.",
model_name="gpt-4o",
)
# Create organizational units with the agents
research_unit = OrganizationalUnit(
name="Research Unit",
description="Handles research and analysis tasks",
manager=research_manager,
members=[data_analyst, research_assistant],
)
development_unit = OrganizationalUnit(
name="Development Unit",
description="Handles development and implementation tasks",
manager=development_manager,
members=[software_engineer, qa_engineer],
)
# Initialize the director agent
director = OpenAIFunctionCaller(
model_name="gpt-4o",
system_prompt=(
"As the Director of this Hierarchical Agent Swarm, you are responsible for:\n"
"1. Analyzing tasks and breaking them down into subtasks\n"
"2. Assigning tasks to appropriate organizational units\n"
"3. Coordinating communication between units\n"
"4. Ensuring tasks are completed efficiently and effectively\n"
"5. Providing feedback and guidance to units as needed\n\n"
"Your decisions should be based on the capabilities of each unit and the requirements of the task."
),
api_key=os.getenv("OPENAI_API_KEY"),
temperature=0.5,
base_model=SwarmSpec,
max_tokens=10000,
)
# Initialize the hierarchical swarm with the organizational units
swarm = HierarchicalSwarm(
name="Example Hierarchical Swarm",
description="A hierarchical swarm demonstrating multi-unit collaboration",
director=director,
organizational_units=[research_unit, development_unit],
max_loops=2, # Allow for feedback and iteration
output_type="dict",
)
# Example task to run through the swarm
task = """
Develop a comprehensive market analysis for a new AI-powered productivity tool.
The analysis should include:
1. Market research and competitor analysis
2. User needs and pain points
3. Technical feasibility assessment
4. Implementation recommendations
"""
# Run the task through the swarm
result = swarm.run(task)
print("Swarm Results:", result)

@ -13,8 +13,6 @@ swarm = HierarchicalSwarm(
agents=[research_agent, analysis_agent],
max_loops=1,
interactive=True, # Enable the Arasaka dashboard
# director_reasoning_enabled=False,
# director_reasoning_model_name="groq/moonshotai/kimi-k2-instruct",
multi_agent_prompt_improvements=True,
)

@ -7,15 +7,6 @@ of the Talk Structurally, Act Hierarchically framework.
All components are now in one file: hierarchical_structured_communication_framework.py
"""
import os
import sys
# Add the project root to the Python path
project_root = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..")
)
sys.path.insert(0, project_root)
from dotenv import load_dotenv
# Import everything from the single file

@ -1,118 +0,0 @@
import os
from dotenv import load_dotenv
from swarms import Agent, SequentialWorkflow
from swarm_models import OpenAIChat
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,
)
# Initialize specialized agents
data_extractor_agent = Agent(
agent_name="Data-Extractor",
system_prompt=None,
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=None,
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=None,
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=None,
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=None,
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 = SequentialWorkflow(
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,
],
output_type="all",
)
# 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",
img=None,
)
print(result)

@ -1,27 +1,10 @@
import os
from dotenv import load_dotenv
from swarms import Agent, SequentialWorkflow
from swarm_models import OpenAIChat
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,
)
# Initialize specialized agents
data_extractor_agent = Agent(
agent_name="Data-Extractor",
system_prompt=None,
llm=model,
model_name="gpt-4.1",
max_loops=1,
autosave=True,
verbose=True,
@ -36,7 +19,7 @@ data_extractor_agent = Agent(
summarizer_agent = Agent(
agent_name="Document-Summarizer",
system_prompt=None,
llm=model,
model_name="gpt-4.1",
max_loops=1,
autosave=True,
verbose=True,
@ -51,7 +34,7 @@ summarizer_agent = Agent(
financial_analyst_agent = Agent(
agent_name="Financial-Analyst",
system_prompt=None,
llm=model,
model_name="gpt-4.1",
max_loops=1,
autosave=True,
verbose=True,
@ -66,7 +49,7 @@ financial_analyst_agent = Agent(
market_analyst_agent = Agent(
agent_name="Market-Analyst",
system_prompt=None,
llm=model,
model_name="gpt-4.1",
max_loops=1,
autosave=True,
verbose=True,
@ -81,7 +64,7 @@ market_analyst_agent = Agent(
operational_analyst_agent = Agent(
agent_name="Operational-Analyst",
system_prompt=None,
llm=model,
model_name="gpt-4.1",
max_loops=1,
autosave=True,
verbose=True,

@ -1,143 +0,0 @@
import os
from dotenv import load_dotenv
from swarms import Agent, SequentialWorkflow
from swarm_models import OpenAIChat
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,
)
# Initialize specialized agents
data_extractor_agent = Agent(
agent_name="Data-Extractor",
system_prompt="""You are a data extraction specialist. Your role is to:
1. Extract key information, data points, and metrics from documents
2. Identify and pull out important facts, figures, and statistics
3. Structure extracted data in a clear, organized format
4. Flag any inconsistencies or missing data
5. Ensure accuracy in data extraction while maintaining context""",
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="""You are a document summarization expert. Your role is to:
1. Create concise, comprehensive summaries of documents
2. Highlight key points and main takeaways
3. Maintain the essential meaning while reducing length
4. Structure summaries in a logical, readable format
5. Identify and emphasize critical insights""",
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="""You are a financial analysis expert. Your role is to:
1. Analyze financial statements and metrics
2. Evaluate company valuations and financial projections
3. Assess financial risks and opportunities
4. Provide insights on financial performance and health
5. Make recommendations based on financial analysis""",
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="""You are a market analysis expert. Your role is to:
1. Analyze market trends and dynamics
2. Evaluate competitive landscape and market positioning
3. Identify market opportunities and threats
4. Assess market size and growth potential
5. Provide strategic market insights and recommendations""",
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="""You are an operational analysis expert. Your role is to:
1. Analyze business operations and processes
2. Evaluate operational efficiency and effectiveness
3. Identify operational risks and opportunities
4. Assess scalability and growth potential
5. Provide recommendations for operational improvements""",
llm=model,
max_loops=2,
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 = SequentialWorkflow(
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,
],
output_type="all",
)
# 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",
no_use_clusterops=True,
)
print(result)

@ -9,10 +9,9 @@ market_researcher = Agent(
3. Evaluating competitor strategies
4. Assessing customer needs and preferences
5. Providing actionable market insights""",
model_name="claude-3-sonnet-20240229",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
streaming_on=True,
)
# Initialize financial analyst agent
@ -24,9 +23,8 @@ financial_analyst = Agent(
3. Assessing risk factors
4. Providing financial forecasts
5. Recommending financial strategies""",
model_name="claude-3-sonnet-20240229",
model_name="gpt-4.1",
max_loops=1,
streaming_on=True,
temperature=0.7,
)
@ -39,10 +37,9 @@ technical_analyst = Agent(
3. Identifying support and resistance levels
4. Assessing market momentum
5. Providing trading recommendations""",
model_name="claude-3-sonnet-20240229",
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
streaming_on=True,
)
# Create list of agents
@ -53,11 +50,9 @@ router = SequentialWorkflow(
name="market-analysis-router",
agents=agents,
max_loops=1,
# output_type="all",
team_awareness=True,
)
result = router.run(
"Analyze Tesla (TSLA) stock from market, financial, and technical perspectives"
)
result = router.run("What are the best 3 oil ETFs?")
print(result)

@ -11,9 +11,6 @@ import sys
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union, Any
import warnings
warnings.filterwarnings("ignore")
import cv2
import numpy as np
import torch
@ -22,6 +19,10 @@ from PIL import Image
import open3d as o3d
from loguru import logger
warnings.filterwarnings("ignore")
# Third-party model imports
try:
import timm

@ -0,0 +1,90 @@
import asyncio
from browser_use import Agent as BrowserAgent
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from swarms import Agent
load_dotenv()
class BrowserUseAgent:
def __init__(self, agent_name: str = "BrowserAgent", agent_description: str = "A browser agent that can navigate the web and perform tasks."):
"""
Initialize a BrowserAgent with a given name.
Args:
agent_name (str): The name of the browser agent.
"""
self.agent_name = agent_name
self.agent_description = agent_description
async def browser_agent_test(self, task: str):
"""
Asynchronously run the browser agent on a given task.
Args:
task (str): The task prompt for the agent.
Returns:
Any: The result of the agent's run method.
"""
agent = BrowserAgent(
task=task,
llm=ChatOpenAI(model="gpt-4.1"),
)
result = await agent.run()
return result.model_dump_json(indent=4)
def run(self, task: str):
"""
Run the browser agent synchronously on a given task.
Args:
task (str): The task prompt for the agent.
Returns:
Any: The result of the agent's run method.
"""
return asyncio.run(self.browser_agent_test(task))
def browser_agent_tool(task: str):
"""
Executes a browser automation agent as a callable tool.
This function instantiates a `BrowserAgent` and runs it synchronously on the provided task prompt.
The agent will use a language model to interpret the task, control a browser, and return the results
as a JSON-formatted string.
Args:
task (str):
A detailed instruction or prompt describing the browser-based task to perform.
For example, you can instruct the agent to navigate to a website, extract information,
or interact with web elements.
Returns:
str:
The result of the browser agent's execution, formatted as a JSON string. The output
typically includes the agent's findings, extracted data, and any relevant observations
from the automated browser session.
Example:
result = browser_agent_tool(
"Please navigate to https://www.coingecko.com and identify the best performing cryptocurrency coin over the past 24 hours."
)
print(result)
"""
return BrowserAgent().run(task)
agent = Agent(
name = "Browser Agent",
model_name = "gpt-4.1",
tools = [browser_agent_tool],
)
agent.run("Please navigate to https://www.coingecko.com and identify the best performing cryptocurrency coin over the past 24 hours.")

@ -0,0 +1,67 @@
import asyncio
from browser_use import Agent
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from swarms import ConcurrentWorkflow
load_dotenv()
class BrowserAgent:
def __init__(self, agent_name: str = "BrowserAgent"):
"""
Initialize a BrowserAgent with a given name.
Args:
agent_name (str): The name of the browser agent.
"""
self.agent_name = agent_name
async def browser_agent_test(self, task: str):
"""
Asynchronously run the browser agent on a given task.
Args:
task (str): The task prompt for the agent.
Returns:
Any: The result of the agent's run method.
"""
agent = Agent(
task=task,
llm=ChatOpenAI(model="gpt-4.1"),
)
result = await agent.run()
return result.model_dump_json(indent=4)
def run(self, task: str):
"""
Run the browser agent synchronously on a given task.
Args:
task (str): The task prompt for the agent.
Returns:
Any: The result of the agent's run method.
"""
return asyncio.run(self.browser_agent_test(task))
swarm = ConcurrentWorkflow(
agents=[BrowserAgent() for _ in range(10)],
)
swarm.run(
"""Please navigate to https://www.coingecko.com and identify the best performing cryptocurrency coin over the past 24 hours.
Your task is to:
1. Go to the main page of CoinGecko.
2. Locate the list of coins and their performance metrics.
3. Determine which coin has the highest positive percentage change in price over the last 24 hours.
4. Report the name, symbol, and 24h percentage gain of this top-performing coin.
5. Briefly describe any notable trends or observations about this coin's recent performance.
Please provide your findings in a clear and concise summary."""
)

@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api"
[tool.poetry]
name = "swarms"
version = "8.1.2"
version = "8.1.3"
description = "Swarms - TGSC"
license = "MIT"
authors = ["Kye Gomez <kye@apac.ai>"]
@ -88,7 +88,7 @@ swarms = "swarms.cli.main:main"
[tool.poetry.group.lint.dependencies]
black = ">=23.1,<26.0"
ruff = ">=0.5.1,<0.12.9"
ruff = ">=0.5.1,<0.12.11"
types-toml = "^0.10.8.1"
types-pytz = ">=2023.3,<2026.0"
types-chardet = "^5.0.4.6"

@ -319,13 +319,20 @@ You are part of a collaborative multi-agent system. Work together to solve compl
### Core Principles
1. **Clarity**: Restate tasks in your own words.
2. **Role Awareness**: Know your role and don't assume others' roles.
3. **Communication**: Share all relevant information and acknowledge others' inputs.
3. **Communication**: Share all relevant information and actively acknowledge and reference other agents' outputs.
4. **Verification**: Use the 3C Protocol (Completeness, Coherence, Correctness).
5. **Reflection**: Continuously evaluate your actions and their impact.
### Key Protocols
- Before acting: Verify if task is already done by others
- During execution: Share reasoning and intermediate steps
- After completion: Get verification from at least one other agent
- Always: Explain your rationale and acknowledge others' contributions
- Before acting: Check and acknowledge if the task or part of it has already been completed by another agent. Reference their output explicitly.
- During execution: Share your reasoning and intermediate steps. When building on or differing from another agent's output, mention them by name and explain your reasoning.
- After completion: Request verification from at least one other agent, and acknowledge their feedback or validation.
- Always: Clearly explain your rationale, and explicitly acknowledge, reference, or build upon the outputs and contributions of other agents.
#### Example Acknowledgement Phrases
- "Building on Agent-2's previous output, I propose..."
- "I have reviewed Agent-3's result and confirm it is correct."
- "Agent-1 raised a good point regarding step 2; I will address it as follows..."
- "My output differs from Agent-4's because..."
"""

@ -1,5 +1,6 @@
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
from typing import Dict, List, Any, Optional
class MCPConnection(BaseModel):
@ -37,7 +38,7 @@ class MCPConnection(BaseModel):
class MultipleMCPConnections(BaseModel):
connections: List[MCPConnection] = Field(
default=[], description="List of MCP connections"
description="List of MCP connections"
)
class Config:

@ -1,5 +1,6 @@
from swarms.structs.agent import Agent
from swarms.structs.agent_builder import AgentsBuilder
from swarms.structs.agent_loader import AgentLoader
from swarms.structs.agent_rearrange import AgentRearrange, rearrange
from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
from swarms.structs.base_structure import BaseStructure
@ -190,4 +191,5 @@ __all__ = [
"check_cancelled",
"check_exit",
"check_end",
"AgentLoader",
]

@ -52,6 +52,7 @@ from swarms.schemas.base_schemas import (
from swarms.schemas.conversation_schema import ConversationSchema
from swarms.schemas.mcp_schemas import (
MCPConnection,
MultipleMCPConnections,
)
from swarms.structs.agent_roles import agent_roles
from swarms.structs.conversation import Conversation
@ -419,6 +420,7 @@ class Agent:
safety_prompt_on: bool = False,
random_models_on: bool = False,
mcp_config: Optional[MCPConnection] = None,
mcp_configs: Optional[MultipleMCPConnections] = None,
top_p: Optional[float] = 0.90,
conversation_schema: Optional[ConversationSchema] = None,
llm_base_url: Optional[str] = None,
@ -571,6 +573,7 @@ class Agent:
self.reasoning_prompt_on = reasoning_prompt_on
self.dynamic_context_window = dynamic_context_window
self.show_tool_execution_output = show_tool_execution_output
self.mcp_configs = mcp_configs
# self.init_handling()
self.setup_config()
@ -1023,16 +1026,16 @@ class Agent:
self.short_memory.add(
role="system",
content=(
f"🔍 [RAG Query Initiated]\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"📝 Query:\n{query}\n\n"
f"📚 Retrieved Knowledge (RAG Output):\n{output}\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"💡 The above information was retrieved from the agent's long-term memory using Retrieval-Augmented Generation (RAG). "
f"Use this context to inform your next response or reasoning step."
"[RAG Query Initiated]\n"
"----------------------------------\n"
f"Query:\n{query}\n\n"
f"Retrieved Knowledge (RAG Output):\n{output}\n"
"----------------------------------\n"
"The above information was retrieved from the agent's long-term memory using Retrieval-Augmented Generation (RAG). "
"Use this context to inform your next response or reasoning step."
),
)
except Exception as e:
except AgentMemoryError as e:
logger.error(
f"Agent: {self.agent_name} Error handling RAG query: {e} Traceback: {traceback.format_exc()}"
)

@ -6,11 +6,11 @@ from swarms.agents.create_agents_from_yaml import (
create_agents_from_yaml,
)
from swarms.structs.agent import Agent
from swarms.structs.csv_to_agent import AgentLoader as CSVAgentLoader
from swarms.structs.csv_to_agent import CSVAgentLoader
from swarms.utils.agent_loader_markdown import (
load_agent_from_markdown,
load_agents_from_markdown,
AgentLoader as MarkdownAgentLoader,
MarkdownAgentLoader,
)
@ -21,10 +21,11 @@ class AgentLoader:
This class provides methods to load agents from Markdown, YAML, and CSV files.
"""
def __init__(self):
def __init__(self, concurrent: bool = True):
"""
Initialize the AgentLoader instance.
"""
self.concurrent = concurrent
pass
def load_agents_from_markdown(

@ -1,12 +1,9 @@
import json
import uuid
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Callable, Dict, List, Optional, Union
from swarms.structs.agent import Agent
from swarms.structs.base_swarm import BaseSwarm
from swarms.structs.conversation import Conversation
from swarms.structs.multi_agent_exec import get_agents_info
from swarms.telemetry.main import log_agent_data
from swarms.utils.any_to_str import any_to_str
from swarms.utils.history_output_formatter import (
@ -14,51 +11,12 @@ from swarms.utils.history_output_formatter import (
)
from swarms.utils.loguru_logger import initialize_logger
from swarms.utils.output_types import OutputType
from swarms.structs.swarm_id import swarm_id
logger = initialize_logger(log_folder="rearrange")
def swarm_id():
return uuid.uuid4().hex
class AgentRearrange(BaseSwarm):
"""
A class representing a swarm of agents for rearranging tasks.
Attributes:
id (str): Unique identifier for the swarm
name (str): Name of the swarm
description (str): Description of the swarm's purpose
agents (callable): Dictionary mapping agent names to Agent objects
flow (str): The flow pattern defining task execution order
max_loops (int): Maximum number of execution loops
verbose (bool): Whether to enable verbose logging
memory_system (BaseVectorDatabase): Memory system for storing agent interactions
human_in_the_loop (bool): Whether human intervention is enabled
custom_human_in_the_loop (Callable): Custom function for human intervention
return_json (bool): Whether to return output in JSON format
output_type (OutputType): Format of output ("all", "final", "list", or "dict")
swarm_history (dict): History of agent interactions
input_config (AgentRearrangeInput): Input configuration schema
output_schema (AgentRearrangeOutput): Output schema
Methods:
__init__(): Initializes the AgentRearrange object
reliability_checks(): Validates swarm configuration
set_custom_flow(): Sets a custom flow pattern
add_agent(): Adds an agent to the swarm
track_history(): Records agent interaction history
remove_agent(): Removes an agent from the swarm
add_agents(): Adds multiple agents to the swarm
validate_flow(): Validates the flow pattern
run(): Executes the swarm's task processing
astream(): Runs the swarm with streaming output
batch_run(): Processes multiple tasks in batches
abatch_run(): Asynchronously processes multiple tasks in batches
concurrent_run(): Processes multiple tasks concurrently
"""
class AgentRearrange:
def __init__(
self,
@ -74,29 +32,17 @@ class AgentRearrange(BaseSwarm):
custom_human_in_the_loop: Optional[
Callable[[str], str]
] = None,
return_json: bool = False,
output_type: OutputType = "all",
docs: List[str] = None,
doc_folder: str = None,
device: str = "cpu",
device_id: int = 0,
all_cores: bool = False,
all_gpus: bool = True,
no_use_clusterops: bool = True,
autosave: bool = True,
return_entire_history: bool = False,
rules: str = None,
team_awareness: bool = False,
time_enabled: bool = False,
message_id_on: bool = False,
*args,
**kwargs,
):
super(AgentRearrange, self).__init__(
name=name,
description=description,
agents=agents if agents else [],
*args,
**kwargs,
)
self.name = name
self.description = description
self.id = id
self.agents = {agent.agent_name: agent for agent in agents}
self.flow = flow if flow is not None else ""
@ -105,29 +51,46 @@ class AgentRearrange(BaseSwarm):
self.memory_system = memory_system
self.human_in_the_loop = human_in_the_loop
self.custom_human_in_the_loop = custom_human_in_the_loop
self.return_json = return_json
self.output_type = output_type
self.docs = docs
self.doc_folder = doc_folder
self.device = device
self.device_id = device_id
self.all_cores = all_cores
self.all_gpus = all_gpus
self.no_use_clusterops = no_use_clusterops
self.autosave = autosave
self.return_entire_history = return_entire_history
self.time_enabled = time_enabled
self.message_id_on = message_id_on
self.conversation = Conversation(
time_enabled=False, token_count=False
name=f"{self.name}-Conversation",
time_enabled=self.time_enabled,
token_count=False,
message_id_on=self.message_id_on,
)
if rules:
self.conversation.add("User", rules)
self.conversation.add("user", rules)
if team_awareness is True:
agents_info = get_agents_info(self.agents, self.name)
# agents_info = get_agents_info(agents=self.agents, team_name=self.name)
# Add sequential flow information if available
sequential_info = self._get_sequential_flow_info()
if sequential_info:
# agents_info += "\n\n" + sequential_info
self.conversation.add("system", sequential_info)
# self.conversation.add("system", agents_info)
self.conversation.add("Your Swarm", agents_info)
self.reliability_check()
def reliability_check(self):
if self.agents is None or len(self.agents) == 0:
raise ValueError("Agents list cannot be None or empty")
if self.max_loops == 0:
raise ValueError("max_loops cannot be 0")
if self.flow is None or self.flow == "":
raise ValueError("flow cannot be None or empty")
if self.output_type is None or self.output_type == "":
raise ValueError("output_type cannot be None or empty")
def set_custom_flow(self, flow: str):
self.flow = flow
@ -213,6 +176,136 @@ class AgentRearrange(BaseSwarm):
logger.info(f"Flow: {self.flow} is valid.")
return True
def _get_sequential_awareness(
self, agent_name: str, tasks: List[str]
) -> str:
"""
Determines the sequential awareness information for an agent in a sequential flow.
Args:
agent_name (str): The name of the current agent.
tasks (List[str]): The list of tasks in the flow.
Returns:
str: A string describing the agents ahead and behind in the sequence.
"""
# Find the position of the current agent in the flow
agent_position = None
for i, task in enumerate(tasks):
agent_names = [name.strip() for name in task.split(",")]
if agent_name in agent_names:
agent_position = i
break
if agent_position is None:
return ""
awareness_info = []
# Check if there's an agent before (ahead in the sequence)
if agent_position > 0:
prev_task = tasks[agent_position - 1]
prev_agents = [
name.strip() for name in prev_task.split(",")
]
if (
prev_agents and prev_agents[0] != "H"
): # Skip human agents
awareness_info.append(
f"Agent ahead: {', '.join(prev_agents)}"
)
# Check if there's an agent after (behind in the sequence)
if agent_position < len(tasks) - 1:
next_task = tasks[agent_position + 1]
next_agents = [
name.strip() for name in next_task.split(",")
]
if (
next_agents and next_agents[0] != "H"
): # Skip human agents
awareness_info.append(
f"Agent behind: {', '.join(next_agents)}"
)
if awareness_info:
return (
f"Sequential awareness: {' | '.join(awareness_info)}"
)
return ""
def _get_sequential_flow_info(self) -> str:
"""
Gets information about the overall sequential flow structure.
Returns:
str: A string describing the sequential flow structure.
"""
if not self.flow or "->" not in self.flow:
return ""
tasks = self.flow.split("->")
flow_info = []
for i, task in enumerate(tasks):
agent_names = [name.strip() for name in task.split(",")]
if (
agent_names and agent_names[0] != "H"
): # Skip human agents
position_info = (
f"Step {i+1}: {', '.join(agent_names)}"
)
if i > 0:
prev_task = tasks[i - 1]
prev_agents = [
name.strip() for name in prev_task.split(",")
]
if prev_agents and prev_agents[0] != "H":
position_info += (
f" (follows: {', '.join(prev_agents)})"
)
if i < len(tasks) - 1:
next_task = tasks[i + 1]
next_agents = [
name.strip() for name in next_task.split(",")
]
if next_agents and next_agents[0] != "H":
position_info += (
f" (leads to: {', '.join(next_agents)})"
)
flow_info.append(position_info)
if flow_info:
return "Sequential Flow Structure:\n" + "\n".join(
flow_info
)
return ""
def get_agent_sequential_awareness(self, agent_name: str) -> str:
"""
Gets the sequential awareness information for a specific agent.
Args:
agent_name (str): The name of the agent to get awareness for.
Returns:
str: A string describing the agents ahead and behind in the sequence.
"""
if not self.flow or "->" not in self.flow:
return ""
tasks = self.flow.split("->")
return self._get_sequential_awareness(agent_name, tasks)
def get_sequential_flow_structure(self) -> str:
"""
Gets the overall sequential flow structure information.
Returns:
str: A string describing the complete sequential flow structure.
"""
return self._get_sequential_flow_info()
def _run(
self,
task: str = None,
@ -319,6 +412,20 @@ class AgentRearrange(BaseSwarm):
agent = self.agents[agent_name]
# Add sequential awareness information for the agent
awareness_info = (
self._get_sequential_awareness(
agent_name, tasks
)
)
if awareness_info:
self.conversation.add(
"system", awareness_info
)
logger.info(
f"Added sequential awareness for {agent_name}: {awareness_info}"
)
current_task = agent.run(
task=self.conversation.get_str(),
img=img,
@ -368,11 +475,6 @@ class AgentRearrange(BaseSwarm):
Args:
task (str, optional): The task to execute. Defaults to None.
img (str, optional): Path to input image if required. Defaults to None.
device (str, optional): Computing device to use ('cpu' or 'gpu'). Defaults to "cpu".
device_id (int, optional): ID of specific device to use. Defaults to 1.
all_cores (bool, optional): Whether to use all CPU cores. Defaults to True.
all_gpus (bool, optional): Whether to use all available GPUs. Defaults to False.
no_use_clusterops (bool, optional): Whether to use clusterops. Defaults to False.
*args: Additional positional arguments passed to _run().
**kwargs: Additional keyword arguments passed to _run().
@ -419,10 +521,6 @@ class AgentRearrange(BaseSwarm):
tasks: List[str],
img: Optional[List[str]] = None,
batch_size: int = 10,
device: str = "cpu",
device_id: int = None,
all_cores: bool = True,
all_gpus: bool = False,
*args,
**kwargs,
) -> List[str]:
@ -456,10 +554,6 @@ class AgentRearrange(BaseSwarm):
self.run(
task=task,
img=img_path,
device=device,
device_id=device_id,
all_cores=all_cores,
all_gpus=all_gpus,
*args,
**kwargs,
)

@ -4,8 +4,6 @@ from tenacity import retry, stop_after_attempt, wait_exponential
from typing import Union, Callable, Any
from swarms import Agent
from swarms.utils.loguru_logger import initialize_logger
# from swarms.utils.lazy_loader import lazy_import_decorator
from swarms.utils.auto_download_check_packages import (
auto_check_and_download_package,
)

@ -1,6 +1,6 @@
import os
import traceback
from typing import List, Optional
from typing import List, Literal, Optional
from dotenv import load_dotenv
from loguru import logger
@ -202,7 +202,6 @@ class SwarmRouterConfig(BaseModel):
def reasoning_agent_run(
self,
task: str,
img: Optional[str] = None,
name: str = None,
@ -257,6 +256,11 @@ class AutoSwarmBuilder:
generate_router_config: bool = False,
interactive: bool = False,
max_tokens: int = 8000,
execution_type: Literal[
"return-agents",
"execute-swarm-router",
"return-agent-configurations",
] = "return-agents",
):
"""Initialize the AutoSwarmBuilder.
@ -277,6 +281,7 @@ class AutoSwarmBuilder:
self.generate_router_config = generate_router_config
self.interactive = interactive
self.max_tokens = max_tokens
self.execution_type = execution_type
self.conversation = Conversation()
self.reliability_check()

@ -1,5 +1,4 @@
import os
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
from functools import lru_cache
from typing import Dict, Optional, Tuple
@ -13,6 +12,8 @@ from swarms.utils.history_output_formatter import (
history_output_formatter,
)
from swarms.structs.swarm_id import swarm_id
class EvaluationError(Exception):
"""Base exception for evaluation-related errors."""
@ -32,13 +33,6 @@ class AggregationError(EvaluationError):
pass
def swarm_id() -> str:
"""
Generate a unique ID for the swarm.
"""
return str(uuid.uuid4())
# Define evaluation dimensions and their evaluation goals
EVAL_DIMENSIONS: Dict[str, str] = {
"accuracy": """Conduct a rigorous factual accuracy assessment of the model's response:

@ -169,7 +169,7 @@ class AgentValidator:
)
class AgentLoader:
class CSVAgentLoader:
"""Class to manage agents through various file formats with type safety and high performance"""
def __init__(

@ -1,12 +1,13 @@
import random
from swarms.structs.base_swarm import BaseSwarm
from typing import List
from swarms.structs.agent import Agent
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime
from swarms.schemas.agent_step_schemas import ManySteps
from typing import List, Optional
import tenacity
from pydantic import BaseModel, Field
from swarms.schemas.agent_step_schemas import ManySteps
from swarms.structs.agent import Agent
from swarms.structs.base_swarm import BaseSwarm
from swarms.utils.loguru_logger import initialize_logger
logger = initialize_logger("round-robin")

@ -1,6 +1,10 @@
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Callable, List, Optional, Union
from swarms.prompts.multi_agent_collab_prompt import (
MULTI_AGENT_COLLAB_PROMPT,
)
from swarms.structs.agent import Agent
from swarms.structs.agent_rearrange import AgentRearrange
from swarms.utils.loguru_logger import initialize_logger
@ -11,17 +15,24 @@ logger = initialize_logger(log_folder="sequential_workflow")
class SequentialWorkflow:
"""
A class that orchestrates the execution of a sequence of agents in a defined workflow.
Args:
name (str, optional): The name of the workflow. Defaults to "SequentialWorkflow".
description (str, optional): A description of the workflow. Defaults to "Sequential Workflow, where agents are executed in a sequence."
agents (List[Agent], optional): A list of agents that will be part of the workflow. Defaults to an empty list.
max_loops (int, optional): The maximum number of times to execute the workflow. Defaults to 1.
output_type (OutputType, optional): The format of the output from the workflow. Defaults to "dict".
shared_memory_system (callable, optional): A callable for managing shared memory between agents. Defaults to None.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
Orchestrates the execution of a sequence of agents in a defined workflow.
This class enables the construction and execution of a workflow where multiple agents
(or callables) are executed in a specified order, passing tasks and optional data
through the chain. It supports both synchronous and asynchronous execution, as well as
batched and concurrent task processing.
Attributes:
id (str): Unique identifier for the workflow instance.
name (str): Human-readable name for the workflow.
description (str): Description of the workflow's purpose.
agents (List[Union[Agent, Callable]]): List of agents or callables to execute in sequence.
max_loops (int): Maximum number of times to execute the workflow.
output_type (OutputType): Format of the output from the workflow.
shared_memory_system (callable): Optional callable for managing shared memory between agents.
multi_agent_collab_prompt (bool): Whether to append a collaborative prompt to each agent.
flow (str): String representation of the agent execution order.
agent_rearrange (AgentRearrange): Internal helper for managing agent execution.
Raises:
ValueError: If the agents list is None or empty, or if max_loops is set to 0.
@ -32,13 +43,33 @@ class SequentialWorkflow:
id: str = "sequential_workflow",
name: str = "SequentialWorkflow",
description: str = "Sequential Workflow, where agents are executed in a sequence.",
agents: List[Union[Agent, Callable]] = [],
agents: List[Union[Agent, Callable]] = None,
max_loops: int = 1,
output_type: OutputType = "dict",
shared_memory_system: callable = None,
multi_agent_collab_prompt: bool = True,
team_awareness: bool = False,
*args,
**kwargs,
):
"""
Initialize a SequentialWorkflow instance.
Args:
id (str, optional): Unique identifier for the workflow. Defaults to "sequential_workflow".
name (str, optional): Name of the workflow. Defaults to "SequentialWorkflow".
description (str, optional): Description of the workflow. Defaults to a standard description.
agents (List[Union[Agent, Callable]], optional): List of agents or callables to execute in sequence.
max_loops (int, optional): Maximum number of times to execute the workflow. Defaults to 1.
output_type (OutputType, optional): Output format for the workflow. Defaults to "dict".
shared_memory_system (callable, optional): Callable for shared memory management. Defaults to None.
multi_agent_collab_prompt (bool, optional): If True, appends a collaborative prompt to each agent.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
Raises:
ValueError: If the agents list is None or empty, or if max_loops is set to 0.
"""
self.id = id
self.name = name
self.description = description
@ -46,6 +77,8 @@ class SequentialWorkflow:
self.max_loops = max_loops
self.output_type = output_type
self.shared_memory_system = shared_memory_system
self.multi_agent_collab_prompt = multi_agent_collab_prompt
self.team_awareness = team_awareness
self.reliability_check()
self.flow = self.sequential_flow()
@ -57,12 +90,41 @@ class SequentialWorkflow:
flow=self.flow,
max_loops=self.max_loops,
output_type=self.output_type,
team_awareness=self.team_awareness,
*args,
**kwargs,
)
def reliability_check(self):
"""
Validates the workflow configuration and prepares agents for execution.
Raises:
ValueError: If the agents list is None or empty, or if max_loops is set to 0.
"""
if self.agents is None or len(self.agents) == 0:
raise ValueError("Agents list cannot be None or empty")
if self.max_loops == 0:
raise ValueError("max_loops cannot be 0")
if self.multi_agent_collab_prompt is True:
for agent in self.agents:
agent.system_prompt += MULTI_AGENT_COLLAB_PROMPT
logger.info(
f"Sequential Workflow Name: {self.name} is ready to run."
)
def sequential_flow(self):
# Only create flow if agents exist
"""
Constructs a string representation of the agent execution order.
Returns:
str: A string showing the order of agent execution (e.g., "AgentA -> AgentB -> AgentC").
Returns an empty string if no valid agent names are found.
"""
if self.agents:
# Create flow by joining agent names with arrows
agent_names = []
for agent in self.agents:
try:
@ -91,15 +153,6 @@ class SequentialWorkflow:
return flow
def reliability_check(self):
if self.agents is None or len(self.agents) == 0:
raise ValueError("Agents list cannot be None or empty")
if self.max_loops == 0:
raise ValueError("max_loops cannot be 0")
logger.info("Checks completed; your swarm is ready.")
def run(
self,
task: str,
@ -113,12 +166,10 @@ class SequentialWorkflow:
Args:
task (str): The task for the agents to execute.
img (Optional[str]): An optional image input for the agents.
device (str): The device to use for the agents to execute. Defaults to "cpu".
all_cores (bool): Whether to utilize all CPU cores. Defaults to False.
all_gpus (bool): Whether to utilize all available GPUs. Defaults to False.
device_id (int): The specific device ID to use for execution. Defaults to 0.
no_use_clusterops (bool): Whether to avoid using cluster operations. Defaults to True.
img (Optional[str], optional): An optional image input for the agents.
imgs (Optional[List[str]], optional): Optional list of images for the agents.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
Returns:
str: The final result after processing through all agents.
@ -127,14 +178,11 @@ class SequentialWorkflow:
ValueError: If the task is None or empty.
Exception: If any error occurs during task execution.
"""
try:
# prompt = f"{MULTI_AGENT_COLLAB_PROMPT}\n\n{task}"
return self.agent_rearrange.run(
task=task,
img=img,
# imgs=imgs,
# *args,
# **kwargs,
)
except Exception as e:
@ -144,6 +192,17 @@ class SequentialWorkflow:
raise e
def __call__(self, task: str, *args, **kwargs):
"""
Allows the SequentialWorkflow instance to be called as a function.
Args:
task (str): The task for the agents to execute.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
Returns:
str: The final result after processing through all agents.
"""
return self.run(task, *args, **kwargs)
def run_batched(self, tasks: List[str]) -> List[str]:
@ -157,7 +216,7 @@ class SequentialWorkflow:
List[str]: A list of final results after processing through all agents.
Raises:
ValueError: If tasks is None or empty.
ValueError: If tasks is None, empty, or contains non-string elements.
Exception: If any error occurs during task execution.
"""
if not tasks or not all(
@ -186,7 +245,7 @@ class SequentialWorkflow:
str: The final result after processing through all agents.
Raises:
ValueError: If task is None or empty.
ValueError: If task is None or not a string.
Exception: If any error occurs during task execution.
"""
if not task or not isinstance(task, str):
@ -211,7 +270,7 @@ class SequentialWorkflow:
List[str]: A list of final results after processing through all agents.
Raises:
ValueError: If tasks is None or empty.
ValueError: If tasks is None, empty, or contains non-string elements.
Exception: If any error occurs during task execution.
"""
if not tasks or not all(
@ -222,7 +281,9 @@ class SequentialWorkflow:
)
try:
with ThreadPoolExecutor() as executor:
with ThreadPoolExecutor(
max_workers=os.cpu_count()
) as executor:
results = [
executor.submit(self.agent_rearrange.run, task)
for task in tasks

@ -0,0 +1,5 @@
from uuid import uuid4
def swarm_id():
return f"swarm-{uuid4().hex}"

@ -1,5 +0,0 @@
import uuid
def generate_swarm_id():
return f"swarm-{uuid.uuid4().hex}"

File diff suppressed because it is too large Load Diff

@ -8,14 +8,11 @@ from swarms.structs.conversation import Conversation
from swarms.utils.history_output_formatter import (
HistoryOutputType,
)
from swarms.structs.swarm_id import swarm_id
logger = initialize_logger(log_folder="swarm_arange")
def swarm_id():
return uuid.uuid4().hex
class SwarmRearrange:
"""
A class representing a swarm of swarms for rearranging tasks.

@ -1,3 +1,8 @@
from swarms.utils.agent_loader_markdown import (
load_agent_from_markdown,
load_agents_from_markdown,
MarkdownAgentLoader,
)
from swarms.utils.check_all_model_max_tokens import (
check_all_model_max_tokens,
)
@ -20,12 +25,6 @@ from swarms.utils.file_processing import (
from swarms.utils.history_output_formatter import (
history_output_formatter,
)
from swarms.utils.agent_loader_markdown import (
load_agent_from_markdown,
load_agents_from_markdown,
)
from swarms.utils.litellm_tokenizer import count_tokens
from swarms.utils.output_types import HistoryOutputType
from swarms.utils.parse_code import extract_code_from_markdown
@ -52,4 +51,5 @@ __all__ = [
"load_agent_from_markdown",
"load_agents_from_markdown",
"dynamic_auto_chunking",
"MarkdownAgentLoader",
]

@ -54,7 +54,7 @@ class MarkdownAgentConfig(BaseModel):
return v
class AgentLoader:
class MarkdownAgentLoader:
"""
Loader for creating agents from markdown files using Claude Code sub-agent format.
@ -444,7 +444,7 @@ def load_agent_from_markdown(file_path: str, **kwargs) -> "Agent":
"""
# Lazy import to avoid circular dependency
loader = AgentLoader()
loader = MarkdownAgentLoader()
return loader.load_single_agent(file_path, **kwargs)
@ -488,7 +488,7 @@ def load_agents_from_markdown(
"""
# Lazy import to avoid circular dependency
loader = AgentLoader()
loader = MarkdownAgentLoader()
return loader.load_agents_from_markdown(
file_paths,
concurrent=concurrent,

@ -0,0 +1,19 @@
import os
def check_swarms_api_key():
"""
Check if the Swarms API key is set.
Returns:
str: The value of the SWARMS_API_KEY environment variable.
Raises:
ValueError: If the SWARMS_API_KEY environment variable is not set.
"""
if os.getenv("SWARMS_API_KEY") is None:
raise ValueError(
"Swarms API key is not set. Please set the SWARMS_API_KEY environment variable. "
"You can get your key here: https://swarms.world/platform/api-keys"
)
return os.getenv("SWARMS_API_KEY")

@ -1,5 +1,6 @@
import threading
import time
import re
from typing import Any, Callable, Dict, List, Optional
from rich.console import Console
@ -14,6 +15,8 @@ from rich.table import Table
from rich.text import Text
from rich.spinner import Spinner
from rich.markdown import Markdown
# Global lock to ensure only a single Rich Live context is active at any moment.
# Rich's Live render is **not** thread-safe; concurrent Live contexts on the same
# console raise runtime errors. Using a module-level lock serialises access and
@ -28,6 +31,168 @@ dashboard_live = None
spinner = Spinner("dots", style="yellow")
class MarkdownOutputHandler:
"""Custom output handler to render content as markdown with simplified syntax highlighting"""
def __init__(self, console: "Console"):
self.console = console
def _clean_output(self, output: str) -> str:
"""Clean up the output for better markdown rendering"""
if not output:
return ""
# Remove log prefixes and timestamps
output = re.sub(
r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \| INFO.*?\|.*?\|",
"",
output,
)
output = re.sub(
r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \| DEBUG.*?\|.*?\|",
"",
output,
)
output = re.sub(
r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \| WARNING.*?\|.*?\|",
"",
output,
)
output = re.sub(
r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \| ERROR.*?\|.*?\|",
"",
output,
)
# Remove spinner characters and progress indicators
output = re.sub(r"[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]", "", output)
output = re.sub(r"⠋ Processing\.\.\.", "", output)
output = re.sub(r"⠙ Processing\.\.\.", "", output)
output = re.sub(r"⠹ Processing\.\.\.", "", output)
output = re.sub(r"⠸ Processing\.\.\.", "", output)
output = re.sub(r"⠼ Processing\.\.\.", "", output)
output = re.sub(r"⠴ Processing\.\.\.", "", output)
output = re.sub(r"⠦ Processing\.\.\.", "", output)
output = re.sub(r"⠧ Processing\.\.\.", "", output)
output = re.sub(r"⠇ Processing\.\.\.", "", output)
output = re.sub(r"⠏ Processing\.\.\.", "", output)
# Remove loop indicators
output = re.sub(r"⠋ Loop \d+/\d+", "", output)
output = re.sub(r"⠙ Loop \d+/\d+", "", output)
output = re.sub(r"⠹ Loop \d+/\d+", "", output)
output = re.sub(r"⠸ Loop \d+/\d+", "", output)
output = re.sub(r"⠼ Loop \d+/\d+", "", output)
output = re.sub(r"⠴ Loop \d+/\d+", "", output)
output = re.sub(r"⠦ Loop \d+/\d+", "", output)
output = re.sub(r"⠧ Loop \d+/\d+", "", output)
output = re.sub(r"⠇ Loop \d+/\d+", "", output)
output = re.sub(r"⠏ Loop \d+/\d+", "", output)
# Remove any remaining log messages
output = re.sub(r"INFO.*?\|.*?\|.*?\|", "", output)
output = re.sub(r"DEBUG.*?\|.*?\|.*?\|", "", output)
output = re.sub(r"WARNING.*?\|.*?\|.*?\|", "", output)
output = re.sub(r"ERROR.*?\|.*?\|.*?\|", "", output)
# Clean up extra whitespace and empty lines
output = re.sub(r"\n\s*\n\s*\n", "\n\n", output)
output = re.sub(r"^\s+", "", output, flags=re.MULTILINE)
output = re.sub(r"\s+$", "", output, flags=re.MULTILINE)
# Remove any remaining plaintext artifacts
output = re.sub(r"Generated content:", "", output)
output = re.sub(r"Evaluation result:", "", output)
output = re.sub(r"Refined content:", "", output)
# Ensure proper markdown formatting
if not output.strip().startswith("#"):
# If no headers, add some structure
lines = output.strip().split("\n")
if len(lines) > 0:
# Add a header for the first meaningful line
first_line = lines[0].strip()
if first_line and not first_line.startswith("**"):
output = f"## {first_line}\n\n" + "\n".join(
lines[1:]
)
return output.strip()
def render_with_simple_syntax_highlighting(
self, content: str
) -> list:
"""Render content with simplified syntax highlighting for code blocks"""
# For now, let's just render everything as markdown to ensure it works
# We can add code block detection back later if needed
return [("markdown", content)]
def render_content_parts(self, parts: list) -> list:
"""Render different content parts with appropriate formatting"""
rendered_parts = []
for part in parts:
if part[0] == "markdown":
# Render markdown
try:
md = Markdown(part[1])
rendered_parts.append(md)
except Exception:
# Fallback to plain text
rendered_parts.append(Text(part[1]))
elif part[0] == "code":
# Code is already rendered as Syntax or Text object
rendered_parts.append(part[1])
return rendered_parts
def render_markdown_output(
self,
content: str,
title: str = "",
border_style: str = "blue",
):
"""Render content as markdown with syntax highlighting"""
if not content or content.strip() == "":
return
# Clean up the output
cleaned_content = self._clean_output(content)
# Render with syntax highlighting
try:
# Split content into parts (markdown and code blocks)
parts = self.render_with_simple_syntax_highlighting(
cleaned_content
)
# Render each part appropriately
rendered_parts = self.render_content_parts(parts)
# Create a group of rendered parts
from rich.console import Group
content_group = Group(*rendered_parts)
self.console.print(
Panel(
content_group,
title=title,
border_style=border_style,
)
)
except Exception:
# Fallback to plain text if rendering fails
self.console.print(
Panel(
cleaned_content,
title=title,
border_style="yellow",
)
)
def choose_random_color():
import random
@ -50,9 +215,12 @@ class Formatter:
A class for formatting and printing rich text to the console.
"""
def __init__(self):
def __init__(self, md: bool = True):
"""
Initializes the Formatter with a Rich Console instance.
Args:
md (bool): Enable markdown output rendering. Defaults to True.
"""
self.console = Console()
self._dashboard_live = None
@ -70,6 +238,11 @@ class Formatter:
]
self._spinner_idx = 0
# Set markdown capability based on user preference
self.markdown_handler = (
MarkdownOutputHandler(self.console) if md else None
)
def _get_status_with_loading(self, status: str) -> Text:
"""
Creates a status text with loading animation for running status.
@ -142,12 +315,40 @@ class Formatter:
if not isinstance(content, str):
content = str(content)
try:
self._print_panel(content, title, style)
except Exception:
# Fallback to basic printing if panel fails
print(f"\n{title}:")
print(content)
# Use markdown rendering if enabled
if self.markdown_handler:
self.markdown_handler.render_markdown_output(
content, title, style
)
else:
# Fallback to original panel printing
try:
self._print_panel(content, title, style)
except Exception:
# Fallback to basic printing if panel fails
print(f"\n{title}:")
print(content)
def print_markdown(
self,
content: str,
title: str = "",
border_style: str = "blue",
) -> None:
"""Print content as markdown with syntax highlighting.
Args:
content (str): The content to display as markdown
title (str): The title of the panel
border_style (str): The border style for the panel
"""
if self.markdown_handler:
self.markdown_handler.render_markdown_output(
content, title, border_style
)
else:
# Fallback to regular panel if markdown is disabled
self.print_panel(content, title, border_style)
def print_table(
self, title: str, data: Dict[str, List[str]]
@ -235,7 +436,7 @@ class Formatter:
def print_streaming_panel(
self,
streaming_response,
title: str = "🤖 Agent Streaming Response",
title: str = "Agent Streaming Response",
style: str = None,
collect_chunks: bool = False,
on_chunk_callback: Optional[Callable] = None,
@ -397,7 +598,7 @@ class Formatter:
def print_agent_dashboard(
self,
agents_data: List[Dict[str, Any]],
title: str = "ConcurrentWorkflow Dashboard",
title: str = "Concurrent Workflow Dashboard",
is_final: bool = False,
) -> None:
"""
@ -440,4 +641,5 @@ class Formatter:
self._dashboard_live = None
formatter = Formatter()
# Global formatter instance with markdown output enabled by default
formatter = Formatter(md=True)

@ -118,6 +118,10 @@ def benchmark_multiple_agents(num_agents=100):
"Throughput",
f"{(num_agents/total_elapsed_time) * 1000:.2f} agents/second",
)
time_table.add_row(
"Agents per Minute",
f"{(num_agents/total_elapsed_time) * 60000:.0f} agents/minute",
)
# Add memory measurements
memory_table.add_row(

@ -5,7 +5,7 @@ import sys
import traceback
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from typing import Any, Dict, List, Optional
import psutil
import requests
@ -95,22 +95,8 @@ class SwarmsIssueReporter:
except:
return "Unknown"
def _get_gpu_info(self) -> Tuple[bool, Optional[str]]:
"""Get GPU information and CUDA availability."""
try:
import torch
cuda_available = torch.cuda.is_available()
if cuda_available:
gpu_info = torch.cuda.get_device_name(0)
return cuda_available, gpu_info
return False, None
except:
return False, None
def _get_system_info(self) -> SwarmSystemInfo:
"""Collect system and Swarms-specific information."""
cuda_available, gpu_info = self._get_gpu_info()
return SwarmSystemInfo(
os_name=platform.system(),
@ -120,8 +106,6 @@ class SwarmsIssueReporter:
memory_usage=psutil.virtual_memory().percent,
disk_usage=psutil.disk_usage("/").percent,
swarms_version=self._get_swarms_version(),
cuda_available=cuda_available,
gpu_info=gpu_info,
)
def _categorize_error(

@ -0,0 +1,549 @@
#!/usr/bin/env python3
"""
Test script demonstrating markdown output functionality with a real swarm
Uses the current state of formatter.py to show agent markdown output capabilities
"""
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
from swarms import Agent
from swarms.structs import (
SequentialWorkflow,
ConcurrentWorkflow,
GroupChat,
)
from swarms.utils.formatter import Formatter
class MarkdownTestSwarm:
"""A test swarm that demonstrates markdown output capabilities"""
def __init__(self):
self.formatter = Formatter(markdown=True)
self.setup_agents()
self.setup_swarm()
def setup_agents(self):
"""Setup specialized agents for markdown testing"""
# Research Agent - Generates structured markdown reports
self.research_agent = Agent(
agent_name="Research Agent",
system_prompt="""You are a research specialist. When given a topic, create a comprehensive markdown report with:
- Clear headers and subheaders
- Code examples when relevant
- Bullet points and numbered lists
- Bold and italic text for emphasis
- Tables for data comparison
- Code blocks with syntax highlighting
Always format your response as clean markdown with proper structure.""",
model_name="gpt-4o-mini", # Use a more capable model
temperature=0.7,
max_tokens=4000,
max_loops=1,
context_length=8000, # Limit context to prevent overflow
return_history=False, # Don't return history to reduce context
)
# Code Analysis Agent - Generates code-heavy markdown
self.code_agent = Agent(
agent_name="Code Analysis Agent",
system_prompt="""You are a code analysis specialist. When given code or programming concepts, create markdown documentation with:
- Syntax-highlighted code blocks
- Function documentation
- Code examples
- Performance analysis
- Best practices
Use proper markdown formatting with code blocks, inline code, and structured content.""",
model_name="gpt-4o-mini", # Use a more capable model
temperature=0.5,
max_tokens=4000,
max_loops=1,
context_length=8000, # Limit context to prevent overflow
return_history=False, # Don't return history to reduce context
)
# Data Visualization Agent - Creates data-focused markdown
self.data_agent = Agent(
agent_name="Data Visualization Agent",
system_prompt="""You are a data visualization specialist. When given data or analysis requests, create markdown reports with:
- Data tables
- Statistical analysis
- Charts and graphs descriptions
- Key insights with bold formatting
- Recommendations in structured lists
Format everything as clean, readable markdown.""",
model_name="gpt-4o-mini", # Use a more capable model
temperature=0.6,
max_tokens=4000,
max_loops=1,
context_length=8000, # Limit context to prevent overflow
return_history=False, # Don't return history to reduce context
)
def setup_swarm(self):
"""Setup the swarm with the agents"""
# Create different swarm types for testing
self.sequential_swarm = SequentialWorkflow(
name="Markdown Test Sequential",
description="Sequential workflow for markdown testing",
agents=[
self.research_agent,
self.code_agent,
self.data_agent,
],
max_loops=1, # Reduce loops to prevent context overflow
)
self.concurrent_swarm = ConcurrentWorkflow(
name="Markdown Test Concurrent",
description="Concurrent workflow for markdown testing",
agents=[
self.research_agent,
self.code_agent,
self.data_agent,
],
max_loops=1, # Reduce loops to prevent context overflow
)
self.groupchat_swarm = GroupChat(
name="Markdown Test Group Chat",
description="A group chat for testing markdown output",
agents=[
self.research_agent,
self.code_agent,
self.data_agent,
],
max_loops=1, # Reduce loops to prevent context overflow
)
# Default swarm for main tests
self.swarm = self.sequential_swarm
def test_basic_markdown_output(self):
"""Test basic markdown output with a simple topic"""
print("\n" + "=" * 60)
print("TEST 1: Basic Markdown Output")
print("=" * 60)
topic = "Python Web Development with FastAPI"
self.formatter.print_panel(
f"Starting research on: {topic}",
title="Research Topic",
style="bold blue",
)
# Run the research agent
result = self.research_agent.run(topic)
self.formatter.print_markdown(
result, title="Research Report", border_style="green"
)
def test_code_analysis_markdown(self):
"""Test markdown output with code analysis"""
print("\n" + "=" * 60)
print("TEST 2: Code Analysis Markdown")
print("=" * 60)
code_sample = """
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
# Test the function
for i in range(10):
print(fibonacci(i))
"""
self.formatter.print_panel(
"Analyzing Python code sample",
title="Code Analysis",
style="bold cyan",
)
# Run the code analysis agent
result = self.code_agent.run(
f"Analyze this Python code and provide improvements:\n\n{code_sample}"
)
self.formatter.print_markdown(
result,
title="Code Analysis Report",
border_style="yellow",
)
def test_data_analysis_markdown(self):
"""Test markdown output with data analysis"""
print("\n" + "=" * 60)
print("TEST 3: Data Analysis Markdown")
print("=" * 60)
data_request = """
Analyze the following dataset:
- Sales: $1.2M (Q1), $1.5M (Q2), $1.8M (Q3), $2.1M (Q4)
- Growth Rate: 8%, 12%, 15%, 18%
- Customer Count: 1000, 1200, 1400, 1600
Provide insights and recommendations in markdown format.
"""
self.formatter.print_panel(
"Analyzing quarterly business data",
title="Data Analysis",
style="bold magenta",
)
# Run the data analysis agent
result = self.data_agent.run(data_request)
self.formatter.print_markdown(
result, title="Data Analysis Report", border_style="red"
)
def test_swarm_collaboration_markdown(self):
"""Test markdown output with swarm collaboration"""
print("\n" + "=" * 60)
print("TEST 4: Swarm Collaboration Markdown")
print("=" * 60)
complex_topic = """
Create a comprehensive guide on building a machine learning pipeline that includes:
1. Data preprocessing techniques
2. Model selection strategies
3. Performance evaluation metrics
4. Deployment considerations
Each agent should contribute their expertise and the final output should be well-formatted markdown.
"""
self.formatter.print_panel(
"Swarm collaboration on ML pipeline guide",
title="Swarm Task",
style="bold green",
)
# Run the swarm
results = self.swarm.run(complex_topic)
# Display individual agent results
# SequentialWorkflow returns a list of results, not a dict
for i, result in enumerate(results, 1):
agent_name = f"Agent {i}"
# Handle different result types
if isinstance(result, dict):
# Extract the output from dict result
result_content = result.get("output", str(result))
else:
result_content = str(result)
self.formatter.print_markdown(
result_content,
title=f"Agent {i}: {agent_name}",
border_style="blue",
)
def test_markdown_toggle_functionality(self):
"""Test the markdown enable/disable functionality"""
print("\n" + "=" * 60)
print("TEST 5: Markdown Toggle Functionality")
print("=" * 60)
test_content = """
# Test Content
This is a **bold** test with `inline code`.
## Code Block
```python
def test_function():
return "Hello, World!"
```
## List
- Item 1
- Item 2
- Item 3
"""
# Test with markdown enabled
self.formatter.print_panel(
"Testing with markdown ENABLED",
title="Markdown Enabled",
style="bold green",
)
self.formatter.print_markdown(test_content, "Markdown Output")
# Disable markdown
self.formatter.disable_markdown()
self.formatter.print_panel(
"Testing with markdown DISABLED",
title="Markdown Disabled",
style="bold red",
)
self.formatter.print_panel(test_content, "Plain Text Output")
# Re-enable markdown
self.formatter.enable_markdown()
self.formatter.print_panel(
"Testing with markdown RE-ENABLED",
title="Markdown Re-enabled",
style="bold blue",
)
self.formatter.print_markdown(
test_content, "Markdown Output Again"
)
def test_different_swarm_types(self):
"""Test markdown output with different swarm types"""
print("\n" + "=" * 60)
print("TEST 6: Different Swarm Types")
print("=" * 60)
simple_topic = (
"Explain the benefits of using Python for data science"
)
# Test Sequential Workflow
print("\n--- Sequential Workflow ---")
self.formatter.print_panel(
"Testing Sequential Workflow (agents work in sequence)",
title="Swarm Type Test",
style="bold blue",
)
sequential_results = self.sequential_swarm.run(simple_topic)
for i, result in enumerate(sequential_results, 1):
# Handle different result types
if isinstance(result, dict):
result_content = result.get("output", str(result))
else:
result_content = str(result)
self.formatter.print_markdown(
result_content,
title=f"Sequential Agent {i}",
border_style="blue",
)
# Test Concurrent Workflow
print("\n--- Concurrent Workflow ---")
self.formatter.print_panel(
"Testing Concurrent Workflow (agents work in parallel)",
title="Swarm Type Test",
style="bold green",
)
concurrent_results = self.concurrent_swarm.run(simple_topic)
for i, result in enumerate(concurrent_results, 1):
# Handle different result types
if isinstance(result, dict):
result_content = result.get("output", str(result))
else:
result_content = str(result)
self.formatter.print_markdown(
result_content,
title=f"Concurrent Agent {i}",
border_style="green",
)
# Test Group Chat
print("\n--- Group Chat ---")
self.formatter.print_panel(
"Testing Group Chat (agents collaborate in conversation)",
title="Swarm Type Test",
style="bold magenta",
)
groupchat_results = self.groupchat_swarm.run(simple_topic)
# Handle different result types for GroupChat
if isinstance(groupchat_results, dict):
result_content = groupchat_results.get(
"output", str(groupchat_results)
)
else:
result_content = str(groupchat_results)
self.formatter.print_markdown(
result_content,
title="Group Chat Result",
border_style="magenta",
)
def test_simple_formatter_only(self):
"""Test just the formatter functionality without agents"""
print("\n" + "=" * 60)
print("TEST 7: Simple Formatter Test (No Agents)")
print("=" * 60)
# Test basic markdown rendering
simple_markdown = """
# Simple Test
This is a **bold** test with `inline code`.
## Code Block
```python
def hello_world():
print("Hello, World!")
return "Success"
```
## List
- Item 1
- Item 2
- Item 3
"""
self.formatter.print_panel(
"Testing formatter without agents",
title="Formatter Test",
style="bold cyan",
)
self.formatter.print_markdown(
simple_markdown,
title="Simple Markdown Test",
border_style="green",
)
# Test toggle functionality
self.formatter.disable_markdown()
self.formatter.print_panel(
"Markdown disabled - this should be plain text",
title="Plain Text Test",
style="bold red",
)
self.formatter.enable_markdown()
def test_error_handling_markdown(self):
"""Test markdown output with error handling"""
print("\n" + "=" * 60)
print("TEST 8: Error Handling in Markdown")
print("=" * 60)
# Test with malformed markdown
malformed_content = """
# Incomplete header
**Unclosed bold
```python
def incomplete_code():
# Missing closing backticks
"""
self.formatter.print_panel(
"Testing error handling with malformed markdown",
title="Error Handling Test",
style="bold yellow",
)
# This should handle the error gracefully
self.formatter.print_markdown(
malformed_content,
title="Malformed Markdown Test",
border_style="yellow",
)
# Test with empty content
self.formatter.print_markdown(
"", title="Empty Content Test", border_style="cyan"
)
# Test with None content
self.formatter.print_markdown(
None, title="None Content Test", border_style="magenta"
)
def run_all_tests(self):
"""Run all markdown output tests"""
print(" Starting Swarm Markdown Output Tests")
print("=" * 60)
try:
# Test 1: Basic markdown output
self.test_basic_markdown_output()
# Test 2: Code analysis markdown
self.test_code_analysis_markdown()
# Test 3: Data analysis markdown
self.test_data_analysis_markdown()
# Test 4: Swarm collaboration
self.test_swarm_collaboration_markdown()
# Test 5: Markdown toggle functionality
self.test_markdown_toggle_functionality()
# Test 6: Different swarm types
self.test_different_swarm_types()
# Test 7: Simple formatter test (no agents)
self.test_simple_formatter_only()
# Test 8: Error handling
self.test_error_handling_markdown()
print("\n" + "=" * 60)
print(" All tests completed successfully!")
print("=" * 60)
except Exception as e:
print(f"\n Test failed with error: {str(e)}")
import traceback
traceback.print_exc()
def main():
"""Main function to run the markdown output tests"""
print("Swarms Markdown Output Test Suite")
print(
"Testing the current state of formatter.py with real swarm agents"
)
print("=" * 60)
# Check environment setup
api_key = os.getenv("OPENAI_API_KEY") or os.getenv(
"SWARMS_API_KEY"
)
if not api_key:
print(
"⚠ Warning: No API key found. Please set OPENAI_API_KEY or SWARMS_API_KEY environment variable."
)
print(
" You can create a .env file with: OPENAI_API_KEY=your_api_key_here"
)
print(
" Or set it in your environment: export OPENAI_API_KEY=your_api_key_here"
)
print()
try:
# Create and run the test swarm
test_swarm = MarkdownTestSwarm()
test_swarm.run_all_tests()
except Exception as e:
print(f"\n Test failed with error: {str(e)}")
print("\n Troubleshooting tips:")
print(
"1. Make sure you have set your API key (OPENAI_API_KEY or SWARMS_API_KEY)"
)
print("2. Check your internet connection")
print("3. Verify you have sufficient API credits")
print("4. Try running with a simpler test first")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()
Loading…
Cancel
Save