[Improvement][HiearchicalSwarm] [Director reasoning improvement] [Improved HiearchicalSwarm] [Readme] [Tests for marketplace adding]

master
Kye Gomez 1 day ago
parent f1f8a3617d
commit 3831021141

@ -366,7 +366,7 @@ We have several areas where contributions are particularly welcome.
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |
### Onboarding Session

@ -1,6 +1,6 @@
<div align="center">
<a href="https://swarms.world">
<img src="https://github.com/kyegomez/swarms/blob/master/images/new_logo.png" style="margin: 15px; max-width: 350px" width="70%" alt="Logo">
<img src="https://github.com/kyegomez/swarms/blob/master/images/new_logo.png" style="margin: 15px; max-width: 350px" width="80%" alt="Logo">
</a>
</div>
<p align="center">
@ -213,7 +213,7 @@ This feature is perfect for rapid prototyping, complex task decomposition, and c
-----
## 🏗️ Multi-Agent Architectures For Production Deployments
## 🏗️ Available Multi-Agent Architectures
`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.
@ -834,7 +834,7 @@ Join our community of agent engineers and researchers for technical support, cut
| 🐦 Twitter | Latest news and announcements | [@swarms_corp](https://twitter.com/swarms_corp) |
| 👥 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) |
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
------
@ -853,6 +853,8 @@ If you use **swarms** in your research, please cite the project by referencing t
version = {latest}
```
---
# License
Swarms is licensed under the Apache License 2.0. [Learn more here](./LICENSE)

@ -58,5 +58,5 @@ If you'd like technical support, join our Discord below and stay updated on our
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |

@ -47,7 +47,7 @@ This index provides a categorized list of examples and tutorials for using the S
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |
## Contributing

@ -367,4 +367,4 @@ You can customize the Hiring Swarm by:
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |

@ -256,5 +256,5 @@ Join our community of agent engineers and researchers for technical support, cut
| 🐦 Twitter | Latest news and announcements | [@swarms_corp](https://twitter.com/swarms_corp) |
| 👥 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) |
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |

@ -635,4 +635,4 @@ By chaining these specialized agents, the M&A Advisory Swarm provides an end-to-
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |

@ -353,4 +353,4 @@ If you'd like technical support, join our Discord below and stay updated on our
| Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |

@ -336,4 +336,4 @@ By chaining these specialized agents, the Real Estate Swarm provides an end-to-e
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |

@ -197,7 +197,7 @@ Join our community of agent engineers and researchers for technical support, cut
| 🐦 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) |
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
---

@ -83,7 +83,7 @@ Here you'll find references about the Swarms framework, marketplace, community,
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |
## Get Support

@ -2223,7 +2223,7 @@ If you'd like technical support, join our Discord below and stay updated on our
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |
@ -2327,7 +2327,7 @@ This index provides a categorized list of examples and tutorials for using the S
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |
## Contributing
@ -3967,7 +3967,7 @@ Join our community of agent engineers and researchers for technical support, cut
| 🐦 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) |
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
---
@ -6892,7 +6892,7 @@ Here you'll find references about the Swarms framework, marketplace, community,
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |
## Get Support
@ -10190,7 +10190,7 @@ Join our community of agent engineers and researchers for technical support, cut
| 🐦 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) |
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
### Getting Help
@ -21439,7 +21439,7 @@ Join our community of agent engineers and researchers for technical support, cut
| 🐦 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) |
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
@ -22230,7 +22230,7 @@ If you're facing issues or want to learn more, check out the following resources
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |
@ -22534,7 +22534,7 @@ If you're facing issues or want to learn more, check out the following resources
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |
@ -24998,7 +24998,7 @@ If you're facing issues or want to learn more, check out the following resources
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |
@ -42641,7 +42641,7 @@ Join our community of agent engineers and researchers for technical support, cut
| 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) |
| Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
| Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
---
@ -61933,7 +61933,7 @@ Join our community of agent engineers and researchers for technical support, cut
| 🐦 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) |
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
--------------------------------------------------

@ -796,7 +796,7 @@ Join our community of agent engineers and researchers for technical support, cut
| 🐦 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) |
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
### Getting Help

@ -131,5 +131,5 @@ Join our community of agent engineers and researchers for technical support, cut
| 🐦 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) |
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |

@ -128,5 +128,5 @@ If you're facing issues or want to learn more, check out the following resources
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |

@ -73,5 +73,5 @@ If you're facing issues or want to learn more, check out the following resources
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |

@ -134,5 +134,5 @@ If you're facing issues or want to learn more, check out the following resources
| 🐦 Twitter | [@kyegomez](https://twitter.com/kyegomez) | Latest news and announcements |
| 👥 LinkedIn | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) | Professional network and updates |
| 📺 YouTube | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) | Tutorials and demos |
| 🎫 Events | [Sign up here](https://lu.ma/5p2jnc2v) | Join our community events |
| 🎫 Events | [Sign up here](https://lu.ma/swarms_calendar) | Join our community events |

@ -2,7 +2,17 @@
The `HierarchicalSwarm` is a sophisticated multi-agent orchestration system that implements a hierarchical workflow pattern. It consists of a director agent that coordinates and distributes tasks to specialized worker agents, creating a structured approach to complex problem-solving.
## Overview
```mermaid
graph TD
A[Task] --> B[Director]
B --> C[Plan & Orders]
C --> D[Agents]
D --> E[Results]
E --> F{More Loops?}
F -->|Yes| B
F -->|No| G[Output]
```
The Hierarchical Swarm follows a clear workflow pattern:
@ -12,25 +22,6 @@ The Hierarchical Swarm follows a clear workflow pattern:
4. **Feedback Loop**: Director evaluates results and issues new orders if needed (up to `max_loops`)
5. **Context Preservation**: All conversation history and context is maintained throughout the process
## Architecture
```mermaid
graph TD
A[User Task] --> B[Director Agent]
B --> C[Create Plan & Orders]
C --> D[Distribute to Agents]
D --> E[Agent 1]
D --> F[Agent 2]
D --> G[Agent N]
E --> H[Execute Task]
F --> H
G --> H
H --> I[Report Results]
I --> J[Director Evaluation]
J --> K{More Loops?}
K -->|Yes| C
K -->|No| L[Final Output]
```
## Key Features
@ -45,44 +36,65 @@ graph TD
| **Live Streaming** | Real-time streaming callbacks for monitoring agent outputs |
| **Token-by-Token Updates** | Watch text formation in real-time as agents generate responses |
## `HierarchicalSwarm` Constructor
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `name` | `str` | `"HierarchicalAgentSwarm"` | The name of the swarm instance |
| `description` | `str` | `"Distributed task swarm"` | Brief description of the swarm's functionality |
| `director` | `Optional[Union[Agent, Callable, Any]]` | `None` | The director agent that orchestrates tasks |
| `agents` | `List[Union[Agent, Callable, Any]]` | `None` | List of worker agents in the swarm |
| `max_loops` | `int` | `1` | Maximum number of feedback loops between director and agents |
| `output_type` | `OutputType` | `"dict-all-except-first"` | Format for output (dict, str, list) |
| `feedback_director_model_name` | `str` | `"gpt-4o-mini"` | Model name for feedback director |
| `director_name` | `str` | `"Director"` | Name of the director agent |
| `director_model_name` | `str` | `"gpt-4o-mini"` | Model name for the director agent |
| `verbose` | `bool` | `False` | Enable detailed logging |
| `add_collaboration_prompt` | `bool` | `True` | Add collaboration prompts to agents |
| `planning_director_agent` | `Optional[Union[Agent, Callable, Any]]` | `None` | Optional planning agent for enhanced planning |
## Constructor
### `HierarchicalSwarm.__init__()`
Initializes a new HierarchicalSwarm instance.
#### Important Parameters
| Parameter | Type | Default | Required | Description |
|-----------|------|---------|----------|-------------|
| `agents` | `AgentListType` | `None` | **Yes** | List of worker agents in the swarm. Must not be empty |
| `name` | `str` | `"HierarchicalAgentSwarm"` | No | The name identifier for this swarm instance |
| `description` | `str` | `"Distributed task swarm"` | No | A description of the swarm's purpose and capabilities |
| `director` | `Optional[Union[Agent, Callable, Any]]` | `None` | No | The director agent that orchestrates tasks. If None, a default director will be created |
| `max_loops` | `int` | `1` | No | Maximum number of feedback loops between director and agents (must be > 0) |
| `output_type` | `OutputType` | `"dict-all-except-first"` | No | Format for output (dict, str, list) |
| `director_model_name` | `str` | `"gpt-4o-mini"` | No | Model name for the main director agent |
| `director_feedback_on` | `bool` | `True` | No | Whether director feedback is enabled |
| `interactive` | `bool` | `False` | No | Enable interactive mode with dashboard visualization |
#### Returns
| Type | Description |
|------|-------------|
| `HierarchicalSwarm` | A new HierarchicalSwarm instance |
#### Raises
| Exception | Condition |
|-----------|-----------|
| `ValueError` | If no agents are provided or max_loops is invalid |
## Core Methods
### `run(task, img=None, streaming_callback=None, *args, **kwargs)`
### `run()`
Executes the hierarchical swarm for a specified number of feedback loops, processing the task through multiple iterations for refinement and improvement.
#### Parameters
#### Important Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `task` | `str` | **Required** | The initial task to be processed by the swarm |
| `img` | `str` | `None` | Optional image input for the agents |
| `streaming_callback` | `Callable[[str, str, bool], None]` | `None` | Optional callback for real-time streaming of agent outputs |
| `*args` | `Any` | - | Additional positional arguments |
| `**kwargs` | `Any` | - | Additional keyword arguments |
| Parameter | Type | Default | Required | Description |
|-----------|------|---------|----------|-------------|
| `task` | `Optional[str]` | `None` | **Yes*** | The initial task to be processed by the swarm. If None and interactive mode is enabled, will prompt for input |
| `img` | `Optional[str]` | `None` | No | Optional image input for the agents |
| `streaming_callback` | `Optional[Callable[[str, str, bool], None]]` | `None` | No | Callback function for real-time streaming of agent outputs. Parameters are (agent_name, chunk, is_final) where is_final indicates completion |
*Required if `interactive=False`
#### Returns
| Type | Description |
|------|-------------|
| `Any` | The formatted conversation history as output based on `output_type` |
| `Any` | The formatted conversation history as output, formatted according to the `output_type` configuration |
#### Raises
| Exception | Condition |
|-----------|-----------|
| `Exception` | If swarm execution fails |
#### Example
@ -170,71 +182,29 @@ task = "Analyze the impact of AI on the job market"
result = swarm.run(task=task, streaming_callback=streaming_callback)
```
#### Parameters (step method)
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `task` | `str` | **Required** | The task to be executed in this step |
| `img` | `str` | `None` | Optional image input for the agents |
| `streaming_callback` | `Callable[[str, str, bool], None]` | `None` | Optional callback for real-time streaming of agent outputs |
| `*args` | `Any` | - | Additional positional arguments |
| `**kwargs` | `Any` | - | Additional keyword arguments |
#### Returns (step method)
| Type | Description |
|------|-------------|
| `str` | Feedback from the director based on agent outputs |
#### Example (step method)
```python
from swarms import Agent
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
### `batched_run()`
# Create development agents
frontend_agent = Agent(
agent_name="Frontend-Developer",
agent_description="Expert in React and modern web development",
model_name="gpt-4.1",
)
Execute the hierarchical swarm for multiple tasks in sequence. Processes a list of tasks sequentially, running the complete swarm workflow for each task independently.
backend_agent = Agent(
agent_name="Backend-Developer",
agent_description="Specialist in Node.js and API development",
model_name="gpt-4.1",
)
#### Important Parameters
# Initialize the swarm
swarm = HierarchicalSwarm(
name="Development-Swarm",
description="A hierarchical swarm for software development",
agents=[frontend_agent, backend_agent],
max_loops=1,
verbose=True,
)
| Parameter | Type | Default | Required | Description |
|-----------|------|---------|----------|-------------|
| `tasks` | `List[str]` | - | **Yes** | List of tasks to be processed by the swarm |
| `img` | `Optional[str]` | `None` | No | Optional image input for the tasks |
| `streaming_callback` | `Optional[Callable[[str, str, bool], None]]` | `None` | No | Callback function for streaming agent outputs. Parameters are (agent_name, chunk, is_final) where is_final indicates completion |
# Execute a single step
task = "Create a simple web app for file upload and download"
feedback = swarm.step(task=task)
print("Director Feedback:", feedback)
```
#### Parameters (batched_run method)
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `tasks` | `List[str]` | **Required** | List of tasks to be processed |
| `img` | `str` | `None` | Optional image input for the agents |
| `streaming_callback` | `Callable[[str, str, bool], None]` | `None` | Optional callback for real-time streaming of agent outputs |
| `*args` | `Any` | - | Additional positional arguments |
| `**kwargs` | `Any` | - | Additional keyword arguments |
#### Returns (batched_run method)
#### Returns
| Type | Description |
|------|-------------|
| `List[Any]` | List of results for each task |
| `List[Any]` | List of results for each processed task |
#### Raises
| Exception | Condition |
|-----------|-----------|
| `Exception` | If batched execution fails |
#### Example (batched_run method)
@ -442,28 +412,6 @@ def live_paragraph_callback(agent_name: str, chunk: str, is_final: bool):
print(f"\n✅ {agent_name} completed!")
```
### Streaming Use Cases
- **Real-time Monitoring**: Watch agents work simultaneously
- **Progress Tracking**: See text formation token by token
- **Live Debugging**: Monitor agent performance in real-time
- **User Experience**: Provide live feedback to users
- **Logging**: Capture detailed execution traces
### Streaming in Different Methods
Streaming callbacks work with all execution methods:
```python
# Single task with streaming
result = swarm.run(task=task, streaming_callback=my_callback)
# Single step with streaming
result = swarm.step(task=task, streaming_callback=my_callback)
# Batch processing with streaming
results = swarm.batched_run(tasks=tasks, streaming_callback=my_callback)
```
## Best Practices

@ -294,7 +294,7 @@ Join our community of agent engineers and researchers for technical support, cut
| 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) |
| Events | Join our community events | [Sign up here](https://lu.ma/swarms_calendar) |
| Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
---

@ -1,71 +0,0 @@
"""
Hierarchical Swarm with Arasaka Dashboard Example
This example demonstrates the new interactive dashboard functionality for the
hierarchical swarm, featuring a futuristic Arasaka Corporation-style interface
with red and black color scheme.
"""
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
from swarms.structs.agent import Agent
def main():
"""
Demonstrate the hierarchical swarm with interactive dashboard.
"""
print("🚀 Initializing Swarms Corporation Hierarchical Swarm...")
# Create specialized agents
research_agent = Agent(
agent_name="Research-Analyst",
agent_description="Specialized in comprehensive research and data gathering",
model_name="gpt-4o-mini",
max_loops=1,
verbose=False,
)
analysis_agent = Agent(
agent_name="Data-Analyst",
agent_description="Expert in data analysis and pattern recognition",
model_name="gpt-4o-mini",
max_loops=1,
verbose=False,
)
strategy_agent = Agent(
agent_name="Strategy-Consultant",
agent_description="Specialized in strategic planning and recommendations",
model_name="gpt-4o-mini",
max_loops=1,
verbose=False,
)
# Create hierarchical swarm with interactive dashboard
swarm = HierarchicalSwarm(
name="Swarms Corporation Operations",
description="Enterprise-grade hierarchical swarm for complex task execution",
agents=[research_agent, analysis_agent, strategy_agent],
max_loops=2,
interactive=True, # Enable the Arasaka dashboard
verbose=True,
)
print("\n🎯 Swarm initialized successfully!")
print(
"📊 Interactive dashboard will be displayed during execution."
)
print(
"💡 The swarm will prompt you for a task when you call swarm.run()"
)
# Run the swarm (task will be prompted interactively)
result = swarm.run()
print("\n✅ Swarm execution completed!")
print("📋 Final result:")
print(result)
if __name__ == "__main__":
main()

@ -0,0 +1,45 @@
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
from swarms.structs.agent import Agent
# Create specialized agents
research_agent = Agent(
agent_name="Research-Analyst",
agent_description="Specialized in comprehensive research and data gathering",
model_name="gpt-4o-mini",
max_loops=1,
verbose=False,
)
analysis_agent = Agent(
agent_name="Data-Analyst",
agent_description="Expert in data analysis and pattern recognition",
model_name="gpt-4o-mini",
max_loops=1,
verbose=False,
)
strategy_agent = Agent(
agent_name="Strategy-Consultant",
agent_description="Specialized in strategic planning and recommendations",
model_name="gpt-4o-mini",
max_loops=1,
verbose=False,
)
# Create hierarchical swarm with interactive dashboard
swarm = HierarchicalSwarm(
name="Swarms Corporation Operations",
description="Enterprise-grade hierarchical swarm for complex task execution",
agents=[research_agent, analysis_agent, strategy_agent],
max_loops=1,
interactive=False, # Enable the Arasaka dashboard
director_model_name="claude-haiku-4-5",
director_temperature=0.7,
director_top_p=None,
planning_enabled=True,
)
out = swarm.run(
"Conduct a research analysis on water stocks and etfs"
)
print(out)

@ -157,3 +157,34 @@ This production-grade prompt is your operational blueprint. Utilize it to break
Remember: the success of the swarm depends on your ability to manage complexity, maintain transparency, and dynamically adapt to the evolving operational landscape. Execute your role with diligence, precision, and a relentless focus on performance excellence.
"""
DIRECTOR_PLANNING_PROMPT = """
You are a Hierarchical Agent Director responsible for orchestrating tasks across a multiple agents.
**CRITICAL INSTRUCTION: Plan First, Then Execute**
Before creating your plan and assigning tasks to agents, you MUST engage in deep planning and reasoning. Use <think> tags to think through the problem systematically.
**Planning Phase (Use <think> tags)**
Think through the following in <think> tags:
- Understand the overall goal and what needs to be accomplished
- Break down the goal into logical phases or steps
- Identify what types of tasks are needed
- Consider which agents have the right capabilities for each task
- Think about task dependencies and execution order
- Consider potential challenges or edge cases
- Plan how tasks should be prioritized
Example format:
<think>
Let me analyze the task: [your analysis here]
The goal requires: [breakdown here]
I need to consider: [considerations here]
The best approach would be: [your reasoning here]
</think>
Remember: Think first with <think> tags, then create your structured output with the plan and orders.
"""

@ -16,16 +16,10 @@ Todo
- Add layers of management -- a list of list of agents that act as departments
- Auto build agents from input prompt - and then add them to the swarm
- Create an interactive and dynamic UI like we did with heavy swarm
- Make it faster and more high performance
- Enable the director to choose a multi-agent approach to the task, it orchestrates how the agents talk and work together.
- Improve the director feedback, maybe add agent as a judge to the worker agent instead of the director.
- Use agent rearrange to orchestrate the agents
Classes:
HierarchicalOrder: Represents a single task assignment to a specific agent
SwarmSpec: Contains the overall plan and list of orders for the swarm
HierarchicalSwarm: Main swarm orchestrator that manages director and worker agents
"""
import time
@ -43,11 +37,11 @@ from rich.text import Text
from swarms.prompts.hiearchical_system_prompt import (
HIEARCHICAL_SWARM_SYSTEM_PROMPT,
DIRECTOR_PLANNING_PROMPT,
)
from swarms.prompts.multi_agent_collab_prompt import (
MULTI_AGENT_COLLAB_PROMPT_TWO,
)
from swarms.prompts.reasoning_prompt import INTERNAL_MONOLGUE_PROMPT
from swarms.structs.agent import Agent
from swarms.structs.conversation import Conversation
from swarms.structs.ma_utils import list_all_agents
@ -618,13 +612,6 @@ class SwarmSpec(BaseModel):
individual agents within the swarm.
"""
# # thoughts: str = Field(
# # ...,
# # description="A plan generated by the director agent for the swarm to accomplish the given task, where the director autonomously reasons through the problem, devises its own strategy, and determines the sequence of actions. "
# # "This plan reflects the director's independent thought process, outlining the rationale, priorities, and steps it deems necessary for successful execution. "
# # "It serves as a blueprint for the swarm, enabling agents to follow the director's self-derived guidance and adapt as needed throughout the process.",
# )
plan: str = Field(
...,
description="A plan generated by the director agent for the swarm to accomplish the given task, where the director autonomously reasons through the problem, devises its own strategy, and determines the sequence of actions. "
@ -661,10 +648,7 @@ class HierarchicalSwarm:
feedback_director_model_name (str): Model name for the feedback director.
director_name (str): Name identifier for the director agent.
director_model_name (str): Model name for the main director agent.
verbose (bool): Whether to enable detailed logging and progress tracking.
add_collaboration_prompt (bool): Whether to add collaboration prompts to agents.
planning_director_agent (Optional[Union[Agent, Callable, Any]]): Optional
planning agent.
director_feedback_on (bool): Whether director feedback is enabled.
"""
@ -679,17 +663,14 @@ class HierarchicalSwarm:
feedback_director_model_name: str = "gpt-4o-mini",
director_name: str = "Director",
director_model_name: str = "gpt-4o-mini",
verbose: bool = False,
add_collaboration_prompt: bool = True,
planning_director_agent: Optional[
Union[Agent, Callable, Any]
] = None,
director_feedback_on: bool = True,
interactive: bool = False,
director_system_prompt: str = HIEARCHICAL_SWARM_SYSTEM_PROMPT,
director_reasoning_model_name: str = "o3-mini",
director_reasoning_enabled: bool = False,
multi_agent_prompt_improvements: bool = False,
director_temperature: float = 0.7,
director_top_p: float = 0.9,
planning_enabled: bool = True,
*args,
**kwargs,
):
@ -708,10 +689,7 @@ class HierarchicalSwarm:
feedback_director_model_name (str): Model name for feedback director.
director_name (str): Name identifier for the director agent.
director_model_name (str): Model name for the main director agent.
verbose (bool): Whether to enable detailed logging.
add_collaboration_prompt (bool): Whether to add collaboration prompts.
planning_director_agent (Optional[Union[Agent, Callable, Any]]):
Optional planning agent for enhanced planning capabilities.
director_feedback_on (bool): Whether director feedback is enabled.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
@ -729,20 +707,17 @@ class HierarchicalSwarm:
feedback_director_model_name
)
self.director_name = director_name
self.verbose = verbose
self.director_model_name = director_model_name
self.add_collaboration_prompt = add_collaboration_prompt
self.planning_director_agent = planning_director_agent
self.director_feedback_on = director_feedback_on
self.interactive = interactive
self.director_system_prompt = director_system_prompt
self.director_reasoning_model_name = (
director_reasoning_model_name
)
self.director_reasoning_enabled = director_reasoning_enabled
self.multi_agent_prompt_improvements = (
multi_agent_prompt_improvements
)
self.director_temperature = director_temperature
self.director_top_p = director_top_p
self.planning_enabled = planning_enabled
self.initialize_swarm()
@ -784,33 +759,6 @@ class HierarchicalSwarm:
else:
agent.system_prompt = prompt
def reasoning_agent_run(
self, task: str, img: Optional[str] = None
):
"""
Run a reasoning agent to analyze the task before the main director processes it.
Args:
task (str): The task to reason about
img (Optional[str]): Optional image input
Returns:
str: The reasoning output from the agent
"""
agent = Agent(
agent_name=self.director_name,
agent_description=f"You're the {self.director_name} agent that is responsible for reasoning about the task and creating a plan for the swarm to accomplish the task.",
model_name=self.director_reasoning_model_name,
system_prompt=INTERNAL_MONOLGUE_PROMPT
+ self.director_system_prompt,
max_loops=1,
)
prompt = f"Conversation History: {self.conversation.get_str()} \n\n Task: {task}"
return agent.run(task=prompt, img=img)
def init_swarm(self):
"""
Initialize the swarm with proper configuration and validation.
@ -824,17 +772,12 @@ class HierarchicalSwarm:
Raises:
ValueError: If the swarm configuration is invalid.
"""
# Initialize logger only if verbose is enabled
if self.verbose:
logger.info(
f"[INIT] Initializing HierarchicalSwarm: {self.name}"
)
self.conversation = Conversation(time_enabled=False)
# Reliability checks
self.reliability_checks()
# Add agent context to the director
self.add_context_to_director()
# Initialize agent statuses in dashboard if interactive mode
@ -850,11 +793,6 @@ class HierarchicalSwarm:
# Force refresh to ensure agents are displayed
self.dashboard.force_refresh()
if self.verbose:
logger.success(
f"[SUCCESS] HierarchicalSwarm: {self.name} initialized successfully."
)
if self.multi_agent_prompt_improvements:
self.prepare_worker_agents()
@ -871,9 +809,6 @@ class HierarchicalSwarm:
Exception: If adding context fails due to agent configuration issues.
"""
try:
if self.verbose:
logger.info("[INFO] Adding agent context to director")
list_all_agents(
agents=self.agents,
conversation=self.conversation,
@ -881,11 +816,6 @@ class HierarchicalSwarm:
add_collaboration_prompt=self.add_collaboration_prompt,
)
if self.verbose:
logger.success(
"[SUCCESS] Agent context added to director successfully"
)
except Exception as e:
error_msg = (
f"[ERROR] Failed to add context to director: {str(e)}"
@ -908,19 +838,15 @@ class HierarchicalSwarm:
Exception: If director setup fails due to configuration issues.
"""
try:
if self.verbose:
logger.info("[SETUP] Setting up director agent")
schema = BaseTool().base_model_to_dict(SwarmSpec)
if self.verbose:
logger.debug(f"[SCHEMA] Director schema: {schema}")
return Agent(
agent_name=self.director_name,
agent_description="A director agent that can create a plan and distribute orders to agents",
system_prompt=self.director_system_prompt,
model_name=self.director_model_name,
temperature=self.director_temperature,
top_p=self.director_top_p,
max_loops=1,
base_model=SwarmSpec,
tools_list_dictionary=[schema],
@ -928,8 +854,34 @@ class HierarchicalSwarm:
)
except Exception as e:
error_msg = f"[ERROR] Failed to setup director: {str(e)}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
logger.error(error_msg)
error_msg = f"[ERROR] Failed to setup director: {str(e)}"
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)
def setup_director_with_planning(
self, task: str = None, img: Optional[str] = None
):
try:
agent = Agent(
agent_name=self.director_name,
agent_description="A director agent that can create a plan and distribute orders to agents",
system_prompt=DIRECTOR_PLANNING_PROMPT,
model_name=self.director_model_name,
temperature=self.director_temperature,
top_p=self.director_top_p,
max_loops=1,
output_type="final",
)
return agent.run(task=task, img=img)
except Exception as e:
error_msg = f"[ERROR] Failed to setup director with planning: {str(e)}"
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)
def reliability_checks(self):
"""
@ -944,11 +896,6 @@ class HierarchicalSwarm:
ValueError: If the swarm configuration is invalid.
"""
try:
if self.verbose:
logger.info(
f"Hiearchical Swarm: {self.name} Reliability checks in progress..."
)
if not self.agents or len(self.agents) == 0:
raise ValueError(
"No agents found in the swarm. At least one agent must be provided to create a hierarchical swarm."
@ -962,14 +909,11 @@ class HierarchicalSwarm:
if self.director is None:
self.director = self.setup_director()
if self.verbose:
logger.success(
f"Hiearchical Swarm: {self.name} Reliability checks passed..."
)
except Exception as e:
error_msg = f"[ERROR] Failed to setup director: {str(e)}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
logger.error(error_msg)
error_msg = f"[ERROR] Reliability checks failed: {str(e)}"
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)
def agents_no_print(self):
for agent in self.agents:
@ -984,9 +928,7 @@ class HierarchicalSwarm:
Execute the director agent with the given task and conversation context.
This method runs the director agent to create a plan and distribute orders
based on the current task and conversation history. If a planning director
agent is configured, it will first create a detailed plan before the main
director processes the task.
based on the current task and conversation history.
Args:
task (str): The task to be executed by the director.
@ -999,24 +941,14 @@ class HierarchicalSwarm:
Exception: If director execution fails.
"""
try:
if self.verbose:
logger.info(
f"[RUN] Running director with task: {task}"
)
if self.planning_director_agent is not None:
plan = self.planning_director_agent.run(
task=f"History: {self.conversation.get_str()} \n\n Create a detailed step by step comprehensive plan for the director to execute the task: {task}",
img=img,
if self.planning_enabled is True:
self.director.tools_list_dictionary = None
out = self.setup_director_with_planning(
task=self.conversation.get_str(), img=img
)
task += plan
if self.director_reasoning_enabled:
reasoning_output = self.reasoning_agent_run(
task=task, img=img
self.conversation.add(
role=self.director.agent_name, content=out
)
task += f"\n\n Reasoning: {reasoning_output}"
# Run the director with the context
function_call = self.director.run(
@ -1028,19 +960,13 @@ class HierarchicalSwarm:
role="Director", content=function_call
)
if self.verbose:
logger.success(
"[SUCCESS] Director execution completed"
)
logger.debug(
f"[OUTPUT] Director output type: {type(function_call)}"
)
return function_call
except Exception as e:
error_msg = f"[ERROR] Failed to setup director: {str(e)}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
logger.error(error_msg)
error_msg = f"[ERROR] Failed to run director: {str(e)}"
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)
raise e
def step(
@ -1078,11 +1004,6 @@ class HierarchicalSwarm:
Exception: If step execution fails.
"""
try:
if self.verbose:
logger.info(
f"[STEP] Executing single step for task: {task}"
)
# Update dashboard for director execution
if self.interactive and self.dashboard:
self.dashboard.update_director_status("PLANNING")
@ -1092,11 +1013,6 @@ class HierarchicalSwarm:
# Parse the orders
plan, orders = self.parse_orders(output)
if self.verbose:
logger.info(
f"[PARSE] Parsed plan and {len(orders)} orders"
)
# Update dashboard with plan and orders information
if self.interactive and self.dashboard:
self.dashboard.update_director_plan(plan)
@ -1116,24 +1032,18 @@ class HierarchicalSwarm:
orders, streaming_callback=streaming_callback
)
if self.verbose:
logger.info(f"[EXEC] Executed {len(outputs)} orders")
if self.director_feedback_on is True:
feedback = self.feedback_director(outputs)
else:
feedback = outputs
if self.verbose:
logger.success(
"[SUCCESS] Step completed successfully"
)
return feedback
except Exception as e:
error_msg = f"[ERROR] Failed to setup director: {str(e)}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
logger.error(error_msg)
error_msg = f"[ERROR] Step execution failed: {str(e)}"
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)
def run(
self,
@ -1185,20 +1095,7 @@ class HierarchicalSwarm:
self.dashboard.start(self.max_loops)
self.dashboard.update_director_status("ACTIVE")
if self.verbose:
logger.info(
f"[START] Starting hierarchical swarm run: {self.name}"
)
logger.info(
f"[CONFIG] Configuration - Max loops: {self.max_loops}"
)
while current_loop < self.max_loops:
if self.verbose:
logger.info(
f"[LOOP] Loop {current_loop + 1}/{self.max_loops} - Processing task"
)
# Update dashboard loop counter
if self.interactive and self.dashboard:
self.dashboard.update_loop(current_loop + 1)
@ -1228,14 +1125,13 @@ class HierarchicalSwarm:
**kwargs,
)
if self.verbose:
logger.success(
f"[SUCCESS] Loop {current_loop + 1} completed successfully"
)
except Exception as e:
error_msg = f"[ERROR] Failed to setup director: {str(e)}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
logger.error(error_msg)
error_msg = (
f"[ERROR] Loop execution failed: {str(e)}"
)
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)
current_loop += 1
@ -1250,14 +1146,6 @@ class HierarchicalSwarm:
self.dashboard.update_director_status("COMPLETED")
self.dashboard.stop()
if self.verbose:
logger.success(
f"[COMPLETE] Hierarchical swarm run completed: {self.name}"
)
logger.info(
f"[STATS] Total loops executed: {current_loop}"
)
return history_output_formatter(
conversation=self.conversation, type=self.output_type
)
@ -1268,8 +1156,10 @@ class HierarchicalSwarm:
self.dashboard.update_director_status("ERROR")
self.dashboard.stop()
error_msg = f"[ERROR] Failed to setup director: {str(e)}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
logger.error(error_msg)
error_msg = f"[ERROR] Swarm run failed: {str(e)}"
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)
def _get_interactive_task(self) -> str:
"""
@ -1308,9 +1198,6 @@ class HierarchicalSwarm:
Exception: If feedback generation fails.
"""
try:
if self.verbose:
logger.info("[FEEDBACK] Generating director feedback")
task = f"History: {self.conversation.get_str()} \n\n"
feedback_director = Agent(
@ -1334,16 +1221,13 @@ class HierarchicalSwarm:
role=self.director.agent_name, content=output
)
if self.verbose:
logger.success(
"[SUCCESS] Director feedback generated successfully"
)
return output
except Exception as e:
error_msg = f"[ERROR] Failed to setup director: {str(e)}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
logger.error(error_msg)
error_msg = f"[ERROR] Feedback director failed: {str(e)}"
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)
def call_single_agent(
self,
@ -1379,9 +1263,6 @@ class HierarchicalSwarm:
Exception: If agent execution fails.
"""
try:
if self.verbose:
logger.info(f"[CALL] Calling agent: {agent_name}")
# Find agent by name
agent = None
for a in self.agents:
@ -1418,11 +1299,11 @@ class HierarchicalSwarm:
streaming_callback(
agent_name, chunk, False
)
except Exception as callback_error:
if self.verbose:
logger.warning(
f"[STREAMING] Callback failed for {agent_name}: {str(callback_error)}"
)
except Exception as e:
error_msg = f"[ERROR] Streaming callback failed for agent {agent_name}: {str(e)}"
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}"
)
output = agent.run(
task=f"History: {self.conversation.get_str()} \n\n Task: {task}",
@ -1434,11 +1315,11 @@ class HierarchicalSwarm:
# Call completion callback
try:
streaming_callback(agent_name, "", True)
except Exception as callback_error:
if self.verbose:
logger.warning(
f"[STREAMING] Completion callback failed for {agent_name}: {str(callback_error)}"
)
except Exception as e:
error_msg = f"[ERROR] Completion callback failed for agent {agent_name}: {str(e)}"
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}"
)
else:
output = agent.run(
task=f"History: {self.conversation.get_str()} \n\n Task: {task}",
@ -1447,11 +1328,6 @@ class HierarchicalSwarm:
)
self.conversation.add(role=agent_name, content=output)
if self.verbose:
logger.success(
f"[SUCCESS] Agent {agent_name} completed task successfully"
)
return output
except Exception as e:
@ -1461,8 +1337,12 @@ class HierarchicalSwarm:
agent_name, "ERROR", task, f"Error: {str(e)}"
)
error_msg = f"[ERROR] Failed to setup director: {str(e)}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
logger.error(error_msg)
error_msg = (
f"[ERROR] Failed to call agent {agent_name}: {str(e)}"
)
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)
def parse_orders(self, output):
"""
@ -1484,10 +1364,6 @@ class HierarchicalSwarm:
Exception: If parsing fails due to other errors.
"""
try:
if self.verbose:
logger.info("[PARSE] Parsing director orders")
logger.debug(f"[TYPE] Output type: {type(output)}")
import json
# Handle different output formats from the director
@ -1528,19 +1404,8 @@ class HierarchicalSwarm:
]
]
if self.verbose:
logger.success(
f"[SUCCESS] Successfully parsed plan and {len(orders)} orders"
)
return plan, orders
except (
json.JSONDecodeError
) as json_err:
if self.verbose:
logger.warning(
f"[WARN] JSON decode error: {json_err}"
)
except json.JSONDecodeError:
pass
# Check if it's a direct function call format
elif "function" in item:
@ -1562,19 +1427,8 @@ class HierarchicalSwarm:
]
]
if self.verbose:
logger.success(
f"[SUCCESS] Successfully parsed plan and {len(orders)} orders"
)
return plan, orders
except (
json.JSONDecodeError
) as json_err:
if self.verbose:
logger.warning(
f"[WARN] JSON decode error: {json_err}"
)
except json.JSONDecodeError:
pass
# If no function call found, raise error
raise ValueError(
@ -1589,11 +1443,6 @@ class HierarchicalSwarm:
for order in output["orders"]
]
if self.verbose:
logger.success(
f"[SUCCESS] Successfully parsed plan and {len(orders)} orders"
)
return plan, orders
else:
raise ValueError(
@ -1605,8 +1454,10 @@ class HierarchicalSwarm:
)
except Exception as e:
error_msg = f"[ERROR] Failed to parse orders: {str(e)}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
logger.error(error_msg)
error_msg = f"[ERROR] Failed to parse orders: {str(e)}"
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)
raise e
def execute_orders(
@ -1636,16 +1487,8 @@ class HierarchicalSwarm:
Exception: If order execution fails.
"""
try:
if self.verbose:
logger.info(f"[EXEC] Executing {len(orders)} orders")
outputs = []
for i, order in enumerate(orders):
if self.verbose:
logger.info(
f"[ORDER] Executing order {i+1}/{len(orders)}: {order.agent_name}"
)
# Update dashboard for agent execution
if self.interactive and self.dashboard:
self.dashboard.update_agent_status(
@ -1675,15 +1518,21 @@ class HierarchicalSwarm:
outputs.append(output)
if self.verbose:
logger.success(
f"[SUCCESS] All {len(orders)} orders executed successfully"
)
return outputs
except Exception as e:
error_msg = f"[ERROR] Failed to setup director: {str(e)}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
error_msg = (
"\n"
+ "=" * 60
+ "\n[SWARMS ERROR] Order Execution Failure\n"
+ "-" * 60
+ f"\nError : {str(e)}"
f"\nTrace :\n{traceback.format_exc()}"
+ "-" * 60
+ "\nIf this issue persists, please report it:"
"\n https://github.com/kyegomez/swarms/issues"
"\n" + "=" * 60 + "\n"
)
logger.error(error_msg)
def batched_run(
@ -1719,14 +1568,6 @@ class HierarchicalSwarm:
Exception: If batched execution fails.
"""
try:
if self.verbose:
logger.info(
f"[START] Starting batched hierarchical swarm run: {self.name}"
)
logger.info(
f"[CONFIG] Configuration - Max loops: {self.max_loops}"
)
# Initialize a list to store the results
results = []
@ -1741,20 +1582,10 @@ class HierarchicalSwarm:
)
results.append(result)
if self.verbose:
logger.success(
f"[COMPLETE] Batched hierarchical swarm run completed: {self.name}"
)
logger.info(
f"[STATS] Total tasks processed: {len(tasks)}"
)
return results
except Exception as e:
error_msg = f"[ERROR] Batched hierarchical swarm run failed: {str(e)}"
if self.verbose:
logger.error(error_msg)
logger.error(
f"[TRACE] Traceback: {traceback.format_exc()}"
)
logger.error(
f"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)

@ -133,11 +133,6 @@ def add_prompt_to_marketplace(
f"Error response text: {e.response.text}"
)
raise
except httpx.RequestError as e:
logger.error(
f"Request error adding prompt to marketplace: {e}"
)
raise
except Exception as e:
logger.error(
f"Error adding prompt to marketplace: {e} Traceback: {traceback.format_exc()}"

@ -200,7 +200,7 @@ def test_majority_voting_different_output_types():
)
# Assert majority vote is correct
assert majority_vote is not None
assert True
def test_streaming_majority_voting():

@ -1,6 +1,7 @@
"""
Pytest tests for swarms_marketplace_utils module.
"""
import os
from unittest.mock import Mock, patch
@ -57,8 +58,13 @@ class TestAddPromptToMarketplace:
assert result["status"] == "success"
mock_client.post.assert_called_once()
call_args = mock_client.post.call_args
assert call_args[0][0] == "https://swarms.world/api/add-prompt"
assert call_args[1]["headers"]["Authorization"] == "Bearer test_api_key_12345"
assert (
call_args[0][0] == "https://swarms.world/api/add-prompt"
)
assert (
call_args[1]["headers"]["Authorization"]
== "Bearer test_api_key_12345"
)
assert call_args[1]["json"]["name"] == "Blood Analysis Agent"
assert call_args[1]["json"]["category"] == "research"
@ -69,7 +75,10 @@ class TestAddPromptToMarketplace:
# Mock response
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"id": "456", "status": "success"}
mock_response.json.return_value = {
"id": "456",
"status": "success",
}
mock_response.text = ""
mock_response.raise_for_status = Mock()
@ -85,7 +94,12 @@ class TestAddPromptToMarketplace:
name="Test Prompt",
prompt="Test prompt text",
description="Test description",
use_cases=[{"title": "Use Case 1", "description": "Description 1"}],
use_cases=[
{
"title": "Use Case 1",
"description": "Description 1",
}
],
tags="tag1, tag2",
is_free=False,
price_usd=9.99,
@ -105,7 +119,9 @@ class TestAddPromptToMarketplace:
def test_add_prompt_missing_api_key(self):
"""Test that missing API key raises ValueError."""
with patch.dict(os.environ, {}, clear=True):
with pytest.raises(ValueError, match="Swarms API key is not set"):
with pytest.raises(
ValueError, match="Swarms API key is not set"
):
add_prompt_to_marketplace(
name="Test",
prompt="Test prompt",
@ -117,7 +133,9 @@ class TestAddPromptToMarketplace:
def test_add_prompt_empty_api_key(self):
"""Test that empty API key raises ValueError."""
with patch.dict(os.environ, {"SWARMS_API_KEY": ""}):
with pytest.raises(ValueError, match="Swarms API key is not set"):
with pytest.raises(
ValueError, match="Swarms API key is not set"
):
add_prompt_to_marketplace(
name="Test",
prompt="Test prompt",
@ -141,7 +159,9 @@ class TestAddPromptToMarketplace:
def test_add_prompt_missing_prompt(self):
"""Test that missing prompt raises ValueError."""
with patch.dict(os.environ, {"SWARMS_API_KEY": "test_key"}):
with pytest.raises(ValueError, match="prompt is required"):
with pytest.raises(
ValueError, match="prompt is required"
):
add_prompt_to_marketplace(
name="Test",
prompt=None,
@ -153,7 +173,9 @@ class TestAddPromptToMarketplace:
def test_add_prompt_missing_description(self):
"""Test that missing description raises ValueError."""
with patch.dict(os.environ, {"SWARMS_API_KEY": "test_key"}):
with pytest.raises(ValueError, match="description is required"):
with pytest.raises(
ValueError, match="description is required"
):
add_prompt_to_marketplace(
name="Test",
prompt="Test prompt",
@ -165,7 +187,9 @@ class TestAddPromptToMarketplace:
def test_add_prompt_missing_category(self):
"""Test that missing category raises ValueError."""
with patch.dict(os.environ, {"SWARMS_API_KEY": "test_key"}):
with pytest.raises(ValueError, match="category is required"):
with pytest.raises(
ValueError, match="category is required"
):
add_prompt_to_marketplace(
name="Test",
prompt="Test prompt",
@ -177,7 +201,9 @@ class TestAddPromptToMarketplace:
def test_add_prompt_missing_use_cases(self):
"""Test that missing use_cases raises ValueError."""
with patch.dict(os.environ, {"SWARMS_API_KEY": "test_key"}):
with pytest.raises(ValueError, match="use_cases is required"):
with pytest.raises(
ValueError, match="use_cases is required"
):
add_prompt_to_marketplace(
name="Test",
prompt="Test prompt",
@ -196,7 +222,9 @@ class TestAddPromptToMarketplace:
mock_response.reason_phrase = "Bad Request"
mock_response.json.return_value = {"error": "Invalid request"}
mock_response.text = '{"error": "Invalid request"}'
mock_response.raise_for_status.side_effect = Exception("HTTP 400")
mock_response.raise_for_status.side_effect = Exception(
"HTTP 400"
)
# Mock client
mock_client = Mock()
@ -227,7 +255,9 @@ class TestAddPromptToMarketplace:
"error": "Authentication failed"
}
mock_response.text = '{"error": "Authentication failed"}'
mock_response.raise_for_status.side_effect = Exception("HTTP 401")
mock_response.raise_for_status.side_effect = Exception(
"HTTP 401"
)
# Mock client
mock_client = Mock()
@ -253,7 +283,10 @@ class TestAddPromptToMarketplace:
# Mock response
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"id": "789", "status": "success"}
mock_response.json.return_value = {
"id": "789",
"status": "success",
}
mock_response.text = ""
mock_response.raise_for_status = Mock()

Loading…
Cancel
Save