@ -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
| 🎫 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)
| 🎫 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) |
| 🎫 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) |
| 🎫 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,
| 🎫 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
| 🎫 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
| 🎫 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
| 🎫 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) |
| 🎫 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) |
| 🎫 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) |
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
| `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 |
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 |
| `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 |
| `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",
@ -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) |
# # 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. "
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.",
logger.debug(f"[SCHEMA] Director schema: {schema}")
returnAgent(
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:
)
exceptExceptionase:
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"
)
defsetup_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",
)
returnagent.run(task=task,img=img)
exceptExceptionase:
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"
)
defreliability_checks(self):
"""
@ -944,11 +896,6 @@ class HierarchicalSwarm:
ValueError:Iftheswarmconfigurationisinvalid.
"""
try:
ifself.verbose:
logger.info(
f"Hiearchical Swarm: {self.name} Reliability checks in progress..."
)
ifnotself.agentsorlen(self.agents)==0:
raiseValueError(
"No agents found in the swarm. At least one agent must be provided to create a hierarchical swarm."
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"
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"
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,
ifself.planning_enabledisTrue:
self.director.tools_list_dictionary=None
out=self.setup_director_with_planning(
task=self.conversation.get_str(),img=img
)
task+=plan
ifself.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
)
ifself.verbose:
logger.success(
"[SUCCESS] Director execution completed"
)
logger.debug(
f"[OUTPUT] Director output type: {type(function_call)}"
)
returnfunction_call
exceptExceptionase:
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"
)
raisee
defstep(
@ -1078,11 +1004,6 @@ class HierarchicalSwarm:
Exception:Ifstepexecutionfails.
"""
try:
ifself.verbose:
logger.info(
f"[STEP] Executing single step for task: {task}"
)
# Update dashboard for director execution
ifself.interactiveandself.dashboard:
self.dashboard.update_director_status("PLANNING")
@ -1092,11 +1013,6 @@ class HierarchicalSwarm:
# Parse the orders
plan,orders=self.parse_orders(output)
ifself.verbose:
logger.info(
f"[PARSE] Parsed plan and {len(orders)} orders"
)
# Update dashboard with plan and orders information
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"
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"
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"
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:Iffeedbackgenerationfails.
"""
try:
ifself.verbose:
logger.info("[FEEDBACK] Generating director feedback")
"[SUCCESS] Director feedback generated successfully"
)
returnoutput
exceptExceptionase:
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"
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"
# Handle different output formats from the director
@ -1528,19 +1404,8 @@ class HierarchicalSwarm:
]
]
ifself.verbose:
logger.success(
f"[SUCCESS] Successfully parsed plan and {len(orders)} orders"
)
returnplan,orders
except(
json.JSONDecodeError
)asjson_err:
ifself.verbose:
logger.warning(
f"[WARN] JSON decode error: {json_err}"
)
exceptjson.JSONDecodeError:
pass
# Check if it's a direct function call format
elif"function"initem:
@ -1562,19 +1427,8 @@ class HierarchicalSwarm:
]
]
ifself.verbose:
logger.success(
f"[SUCCESS] Successfully parsed plan and {len(orders)} orders"
)
returnplan,orders
except(
json.JSONDecodeError
)asjson_err:
ifself.verbose:
logger.warning(
f"[WARN] JSON decode error: {json_err}"
)
exceptjson.JSONDecodeError:
pass
# If no function call found, raise error
raiseValueError(
@ -1589,11 +1443,6 @@ class HierarchicalSwarm:
fororderinoutput["orders"]
]
ifself.verbose:
logger.success(
f"[SUCCESS] Successfully parsed plan and {len(orders)} orders"
)
returnplan,orders
else:
raiseValueError(
@ -1605,8 +1454,10 @@ class HierarchicalSwarm:
)
exceptExceptionase:
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"
f"[ORDER] Executing order {i+1}/{len(orders)}: {order.agent_name}"
)
# Update dashboard for agent execution
ifself.interactiveandself.dashboard:
self.dashboard.update_agent_status(
@ -1675,15 +1518,21 @@ class HierarchicalSwarm:
outputs.append(output)
ifself.verbose:
logger.success(
f"[SUCCESS] All {len(orders)} orders executed successfully"
)
returnoutputs
exceptExceptionase:
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"
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)
ifself.verbose:
logger.success(
f"[COMPLETE] Batched hierarchical swarm run completed: {self.name}"
)
logger.info(
f"[STATS] Total tasks processed: {len(tasks)}"
)
returnresults
exceptExceptionase:
error_msg=f"[ERROR] Batched hierarchical swarm run failed: {str(e)}"
ifself.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"