@ -18,6 +18,9 @@ Todo
- 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
@ -25,14 +28,26 @@ Classes:
HierarchicalSwarm : Main swarm orchestrator that manages director and worker agents
"""
import time
import traceback
from typing import Any , Callable , List , Optional , Union
from loguru import logger
from pydantic import BaseModel , Field
from rich . console import Console
from rich . layout import Layout
from rich . live import Live
from rich . panel import Panel
from rich . table import Table
from rich . text import Text
from swarms . prompts . hiearchical_system_prompt import (
HIEARCHICAL_SWARM_SYSTEM_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
@ -40,10 +55,507 @@ from swarms.tools.base_tool import BaseTool
from swarms . utils . history_output_formatter import (
history_output_formatter ,
)
from swarms . utils . loguru_logger import initialize_logger
from swarms . utils . output_types import OutputType
logger = initialize_logger ( log_folder = " hierarchical_swarm " )
class HierarchicalSwarmDashboard :
"""
Futuristic Arasaka Corporation - style dashboard for hierarchical swarm monitoring .
This dashboard provides a professional , enterprise - grade interface with red and black
color scheme , real - time monitoring of swarm operations , and cyberpunk aesthetics .
Attributes :
console ( Console ) : Rich console instance for rendering
live_display ( Live ) : Live display for real - time updates
swarm_name ( str ) : Name of the swarm being monitored
agent_statuses ( dict ) : Current status of all agents
director_status ( str ) : Current status of the director
current_loop ( int ) : Current execution loop
max_loops ( int ) : Maximum number of loops
is_active ( bool ) : Whether the dashboard is currently active
"""
def __init__ ( self , swarm_name : str = " Swarms Corporation " ) :
"""
Initialize the Arasaka dashboard .
Args :
swarm_name ( str ) : Name of the swarm to display in the dashboard
"""
self . console = Console ( )
self . live_display = None
self . swarm_name = swarm_name
self . agent_statuses = { }
self . director_status = " INITIALIZING "
self . current_loop = 0
self . max_loops = 1
self . is_active = False
self . start_time = None
self . spinner_frames = [
" ⠋ " ,
" ⠙ " ,
" ⠹ " ,
" ⠸ " ,
" ⠼ " ,
" ⠴ " ,
" ⠦ " ,
" ⠧ " ,
" ⠇ " ,
" ⠏ " ,
]
self . spinner_idx = 0
# Director information tracking
self . director_plan = " "
self . director_orders = [ ]
# Swarm information
self . swarm_description = " "
self . director_name = " Director "
self . director_model_name = " gpt-4o-mini "
# View mode for agents display
self . detailed_view = False
# Multi-loop agent tracking
self . agent_history = { } # Track agent outputs across loops
self . current_loop = 0
def _get_spinner ( self ) - > str :
""" Get current spinner frame for loading animations. """
self . spinner_idx = ( self . spinner_idx + 1 ) % len (
self . spinner_frames
)
return self . spinner_frames [ self . spinner_idx ]
def _create_header ( self ) - > Panel :
""" Create the dashboard header with Swarms Corporation branding. """
header_text = Text ( )
header_text . append (
" ╔══════════════════════════════════════════════════════════════════════════════╗ \n " ,
style = " bold red " ,
)
header_text . append ( " ║ " , style = " bold red " )
header_text . append ( " " , style = " bold red " )
header_text . append (
" SWARMS CORPORATION " , style = " bold white on red "
)
header_text . append ( " " , style = " bold red " )
header_text . append ( " ║ \n " , style = " bold red " )
header_text . append ( " ║ " , style = " bold red " )
header_text . append ( " " , style = " bold red " )
header_text . append (
" HIERARCHICAL SWARM OPERATIONS CENTER " , style = " bold red "
)
header_text . append ( " " , style = " bold red " )
header_text . append ( " ║ \n " , style = " bold red " )
header_text . append (
" ╚══════════════════════════════════════════════════════════════════════════════╝ " ,
style = " bold red " ,
)
return Panel (
header_text ,
border_style = " red " ,
padding = ( 0 , 1 ) ,
)
def _create_status_panel ( self ) - > Panel :
""" Create the operations status panel. """
status_text = Text ( )
# Corporation branding and operation type
status_text . append (
" By the Swarms Corporation " , style = " bold cyan "
)
status_text . append ( " \n " , style = " white " )
status_text . append (
" Hierarchical Agent Operations " , style = " bold white "
)
status_text . append ( " \n \n " , style = " white " )
# Swarm information
status_text . append ( " SWARM NAME: " , style = " bold white " )
status_text . append ( f " { self . swarm_name } " , style = " bold cyan " )
status_text . append ( " \n " , style = " white " )
status_text . append ( " DESCRIPTION: " , style = " bold white " )
status_text . append ( f " { self . swarm_description } " , style = " white " )
status_text . append ( " \n " , style = " white " )
status_text . append ( " DIRECTOR: " , style = " bold white " )
status_text . append (
f " { self . director_name } ( { self . director_model_name } ) " ,
style = " cyan " ,
)
status_text . append ( " \n " , style = " white " )
status_text . append ( " TOTAL LOOPS: " , style = " bold white " )
status_text . append ( f " { self . max_loops } " , style = " bold cyan " )
status_text . append ( " | " , style = " white " )
status_text . append ( " CURRENT LOOP: " , style = " bold white " )
status_text . append (
f " { self . current_loop } " , style = " bold yellow "
)
# Agent count metadata
agent_count = len ( getattr ( self , " agent_history " , { } ) )
status_text . append ( " | " , style = " white " )
status_text . append ( " AGENTS: " , style = " bold white " )
status_text . append ( f " { agent_count } " , style = " bold green " )
status_text . append ( " \n \n " , style = " white " )
# Director status
status_text . append ( " DIRECTOR STATUS: " , style = " bold white " )
if self . director_status == " INITIALIZING " :
status_text . append (
f " { self . _get_spinner ( ) } { self . director_status } " ,
style = " bold yellow " ,
)
elif self . director_status == " ACTIVE " :
status_text . append (
f " ✓ { self . director_status } " , style = " bold green "
)
elif self . director_status == " PROCESSING " :
status_text . append (
f " { self . _get_spinner ( ) } { self . director_status } " ,
style = " bold cyan " ,
)
else :
status_text . append (
f " ✗ { self . director_status } " , style = " bold red "
)
status_text . append ( " \n \n " , style = " white " )
# Runtime and completion information
if self . start_time :
runtime = time . time ( ) - self . start_time
status_text . append ( " RUNTIME: " , style = " bold white " )
status_text . append ( f " { runtime : .2f } s " , style = " bold green " )
# Add completion percentage if loops are running
if self . max_loops > 0 :
completion_percent = (
self . current_loop / self . max_loops
) * 100
status_text . append ( " | " , style = " white " )
status_text . append ( " PROGRESS: " , style = " bold white " )
status_text . append (
f " { completion_percent : .1f } % " , style = " bold cyan "
)
return Panel (
status_text ,
border_style = " red " ,
padding = ( 1 , 2 ) ,
title = " [bold white]OPERATIONS STATUS[/bold white] " ,
)
def _create_agents_table ( self ) - > Table :
""" Create the agents monitoring table with full outputs and loop history. """
table = Table (
show_header = True ,
header_style = " bold white on red " ,
border_style = " red " ,
title = " [bold white]AGENT MONITORING MATRIX[/bold white] " ,
title_style = " bold white " ,
show_lines = True ,
)
table . add_column ( " AGENT ID " , style = " bold cyan " , width = 25 )
table . add_column ( " LOOP " , style = " bold white " , width = 8 )
table . add_column ( " STATUS " , style = " bold white " , width = 15 )
table . add_column ( " TASK " , style = " white " , width = 40 )
table . add_column ( " OUTPUT " , style = " white " , width = 150 )
# Display agents with their history across loops
for agent_name , history in self . agent_history . items ( ) :
for loop_num in range ( self . max_loops + 1 ) :
loop_key = f " Loop_ { loop_num } "
if loop_key in history :
loop_data = history [ loop_key ]
status = loop_data . get ( " status " , " UNKNOWN " )
task = loop_data . get ( " task " , " N/A " )
output = loop_data . get ( " output " , " " )
# Style status
if status == " RUNNING " :
status_display = (
f " { self . _get_spinner ( ) } { status } "
)
status_style = " bold yellow "
elif status == " COMPLETED " :
status_display = f " ✓ { status } "
status_style = " bold green "
elif status == " PENDING " :
status_display = f " ○ { status } "
status_style = " bold red "
else :
status_display = f " ✗ { status } "
status_style = " bold red "
# Show full output without truncation
output_display = output if output else " No output "
table . add_row (
Text ( agent_name , style = " bold cyan " ) ,
Text ( f " Loop { loop_num } " , style = " bold white " ) ,
Text ( status_display , style = status_style ) ,
Text ( task , style = " white " ) ,
Text ( output_display , style = " white " ) ,
)
return table
def _create_detailed_agents_view ( self ) - > Panel :
""" Create a detailed view of agents with full outputs and loop history. """
detailed_text = Text ( )
for agent_name , history in self . agent_history . items ( ) :
detailed_text . append (
f " AGENT: { agent_name } \n " , style = " bold cyan "
)
detailed_text . append ( " = " * 80 + " \n " , style = " red " )
for loop_num in range ( self . max_loops + 1 ) :
loop_key = f " Loop_ { loop_num } "
if loop_key in history :
loop_data = history [ loop_key ]
status = loop_data . get ( " status " , " UNKNOWN " )
task = loop_data . get ( " task " , " N/A " )
output = loop_data . get ( " output " , " " )
detailed_text . append (
f " LOOP { loop_num } : \n " , style = " bold white "
)
detailed_text . append (
f " STATUS: { status } \n " , style = " bold white "
)
detailed_text . append (
f " TASK: { task } \n " , style = " white "
)
detailed_text . append (
" OUTPUT: \n " , style = " bold white "
)
detailed_text . append ( f " { output } \n " , style = " white " )
detailed_text . append ( " ─ " * 80 + " \n " , style = " red " )
return Panel (
detailed_text ,
border_style = " red " ,
padding = ( 1 , 2 ) ,
title = " [bold white]DETAILED AGENT OUTPUTS (FULL HISTORY)[/bold white] " ,
)
def _create_director_panel ( self ) - > Panel :
""" Create the director information panel showing plan and orders. """
director_text = Text ( )
# Plan section
director_text . append ( " DIRECTOR PLAN: \n " , style = " bold white " )
if self . director_plan :
director_text . append ( self . director_plan , style = " white " )
else :
director_text . append (
" No plan available " , style = " dim white "
)
director_text . append ( " \n \n " , style = " white " )
# Orders section
director_text . append ( " CURRENT ORDERS: \n " , style = " bold white " )
if self . director_orders :
for i , order in enumerate (
self . director_orders
) : # Show first 5 orders
director_text . append ( f " { i + 1 } . " , style = " bold cyan " )
director_text . append (
f " { order . get ( ' agent_name ' , ' Unknown ' ) } : " ,
style = " bold white " ,
)
task = order . get ( " task " , " No task " )
director_text . append ( task , style = " white " )
director_text . append ( " \n " , style = " white " )
if len ( self . director_orders ) > 5 :
director_text . append (
f " ... and { len ( self . director_orders ) - 5 } more orders " ,
style = " dim white " ,
)
else :
director_text . append (
" No orders available " , style = " dim white "
)
return Panel (
director_text ,
border_style = " red " ,
padding = ( 1 , 2 ) ,
title = " [bold white]DIRECTOR OPERATIONS[/bold white] " ,
)
def _create_dashboard_layout ( self ) - > Layout :
""" Create the complete dashboard layout. """
layout = Layout ( )
# Split into operations status, director operations, and agents
layout . split_column (
Layout ( name = " operations_status " , size = 12 ) ,
Layout ( name = " director_operations " , size = 12 ) ,
Layout ( name = " agents " , ratio = 1 ) ,
)
# Add content to each section
layout [ " operations_status " ] . update (
self . _create_status_panel ( )
)
layout [ " director_operations " ] . update (
self . _create_director_panel ( )
)
# Choose between table view and detailed view
if self . detailed_view :
layout [ " agents " ] . update (
self . _create_detailed_agents_view ( )
)
else :
layout [ " agents " ] . update (
Panel (
self . _create_agents_table ( ) ,
border_style = " red " ,
padding = ( 1 , 1 ) ,
)
)
return layout
def start ( self , max_loops : int = 1 ) :
""" Start the dashboard display. """
self . max_loops = max_loops
self . start_time = time . time ( )
self . is_active = True
self . live_display = Live (
self . _create_dashboard_layout ( ) ,
console = self . console ,
refresh_per_second = 10 ,
transient = False ,
)
self . live_display . start ( )
def update_agent_status (
self ,
agent_name : str ,
status : str ,
task : str = " " ,
output : str = " " ,
) :
""" Update the status of a specific agent. """
# Create loop key for tracking history
loop_key = f " Loop_ { self . current_loop } "
# Initialize agent history if not exists
if agent_name not in self . agent_history :
self . agent_history [ agent_name ] = { }
# Store current status and add to history
self . agent_statuses [ agent_name ] = {
" status " : status ,
" task " : task ,
" output " : output ,
}
# Add to history for this loop
self . agent_history [ agent_name ] [ loop_key ] = {
" status " : status ,
" task " : task ,
" output " : output ,
}
if self . live_display and self . is_active :
self . live_display . update ( self . _create_dashboard_layout ( ) )
def update_director_status ( self , status : str ) :
""" Update the director status. """
self . director_status = status
if self . live_display and self . is_active :
self . live_display . update ( self . _create_dashboard_layout ( ) )
def update_loop ( self , current_loop : int ) :
""" Update the current execution loop. """
self . current_loop = current_loop
if self . live_display and self . is_active :
self . live_display . update ( self . _create_dashboard_layout ( ) )
def update_director_plan ( self , plan : str ) :
""" Update the director ' s plan. """
self . director_plan = plan
if self . live_display and self . is_active :
self . live_display . update ( self . _create_dashboard_layout ( ) )
def update_director_orders ( self , orders : list ) :
""" Update the director ' s orders. """
self . director_orders = orders
if self . live_display and self . is_active :
self . live_display . update ( self . _create_dashboard_layout ( ) )
def stop ( self ) :
""" Stop the dashboard display. """
self . is_active = False
if self . live_display :
self . live_display . stop ( )
self . console . print ( )
def update_swarm_info (
self ,
name : str ,
description : str ,
max_loops : int ,
director_name : str ,
director_model_name : str ,
) :
""" Update the dashboard with swarm-specific information. """
self . swarm_name = name
self . swarm_description = description
self . max_loops = max_loops
self . director_name = director_name
self . director_model_name = director_model_name
if self . live_display and self . is_active :
self . live_display . update ( self . _create_dashboard_layout ( ) )
def force_refresh ( self ) :
""" Force refresh the dashboard display. """
if self . live_display and self . is_active :
self . live_display . update ( self . _create_dashboard_layout ( ) )
def show_full_output ( self , agent_name : str , full_output : str ) :
""" Display full agent output in a separate panel. """
if self . live_display and self . is_active :
# Create a full output panel
output_panel = Panel (
Text ( full_output , style = " white " ) ,
title = f " [bold white]FULL OUTPUT - { agent_name } [/bold white] " ,
border_style = " red " ,
padding = ( 1 , 2 ) ,
width = 120 ,
)
# Temporarily show the full output
self . console . print ( output_panel )
self . console . print ( ) # Add spacing
def toggle_detailed_view ( self ) :
""" Toggle between table view and detailed view. """
self . detailed_view = not self . detailed_view
if self . live_display and self . is_active :
self . live_display . update ( self . _create_dashboard_layout ( ) )
class HierarchicalOrder ( BaseModel ) :
@ -71,6 +583,25 @@ class HierarchicalOrder(BaseModel):
)
class HierarchicalOrderRearrange ( BaseModel ) :
"""
Represents a single task assignment within the hierarchical swarm .
This class defines the structure for individual task orders that the director
distributes to worker agents . Each order specifies which agent should execute
what specific task .
"""
initial_task : str = Field (
. . . ,
description = " The initial task that the director has to execute. " ,
)
flow_of_communication : str = Field (
. . . ,
description = " How the agents will communicate with each other to accomplish the task. Like agent_one -> agent_two -> agent_three -> agent_four -> agent_one, can use comma signs to denote sequential communication and commas to denote parallel communication for example agent_one -> agent_two, agent_three -> agent_four " ,
)
class SwarmSpec ( BaseModel ) :
"""
Defines the complete specification for a hierarchical swarm execution .
@ -86,10 +617,20 @@ 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 = " Outlines the sequence of actions to be taken by the swarm. This plan is a detailed roadmap that guides the swarm ' s behavior and decision-making. " ,
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. " ,
)
orders : List [ HierarchicalOrder ] = Field (
. . . ,
description = " A collection of task assignments to specific agents within the swarm. These orders are the specific instructions that guide the agents in their task execution and are a key element in the swarm ' s plan. " ,
@ -143,6 +684,11 @@ class HierarchicalSwarm:
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 = True ,
multi_agent_prompt_improvements : bool = False ,
* args ,
* * kwargs ,
) :
@ -187,9 +733,79 @@ class HierarchicalSwarm:
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
)
if self . interactive :
self . agents_no_print ( )
# Initialize dashboard if interactive mode is enabled
self . dashboard = None
if self . interactive :
self . dashboard = HierarchicalSwarmDashboard ( self . name )
# Enable detailed view for better output visibility
self . dashboard . detailed_view = True
# Pass additional swarm information to dashboard
self . dashboard . update_swarm_info (
name = self . name ,
description = self . description ,
max_loops = self . max_loops ,
director_name = self . director_name ,
director_model_name = self . director_model_name ,
)
self . init_swarm ( )
def list_worker_agents ( self ) - > str :
return list_all_agents (
agents = self . agents ,
add_to_conversation = False ,
)
def prepare_worker_agents ( self ) :
for agent in self . agents :
prompt = (
MULTI_AGENT_COLLAB_PROMPT_TWO
+ self . list_worker_agents ( )
)
if hasattr ( agent , " system_prompt " ) :
agent . system_prompt + = prompt
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 .
@ -216,11 +832,27 @@ class HierarchicalSwarm:
self . add_context_to_director ( )
# Initialize agent statuses in dashboard if interactive mode
if self . interactive and self . dashboard :
for agent in self . agents :
if hasattr ( agent , " agent_name " ) :
self . dashboard . update_agent_status (
agent . agent_name ,
" PENDING " ,
" Awaiting task assignment " ,
" Ready for deployment " ,
)
# Force refresh to ensure agents are displayed
self . dashboard . force_refresh ( )
if self . verbose :
logger . success (
f " ✅ HierarchicalSwarm: { self . name } initialized successfully. "
)
if self . multi_agent_prompt_improvements :
self . prepare_worker_agents ( )
def add_context_to_director ( self ) :
"""
Add agent context and collaboration information to the director ' s conversation.
@ -282,6 +914,7 @@ class HierarchicalSwarm:
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 ,
max_loops = 1 ,
base_model = SwarmSpec ,
@ -333,6 +966,10 @@ class HierarchicalSwarm:
error_msg = f " ❌ Failed to setup director: { str ( e ) } \n 🔍 Traceback: { traceback . format_exc ( ) } \n 🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues "
logger . error ( error_msg )
def agents_no_print ( self ) :
for agent in self . agents :
agent . print_on = False
def run_director (
self ,
task : str ,
@ -358,9 +995,7 @@ class HierarchicalSwarm:
"""
try :
if self . verbose :
logger . info (
f " 🎯 Running director with task: { task [ : 100 ] } ... "
)
logger . info ( f " 🎯 Running director with task: { task } " )
if self . planning_director_agent is not None :
plan = self . planning_director_agent . run (
@ -370,6 +1005,12 @@ class HierarchicalSwarm:
task + = plan
if self . director_reasoning_enabled :
reasoning_output = self . reasoning_agent_run (
task = task , img = img
)
task + = f " \n \n Reasoning: { reasoning_output } "
# Run the director with the context
function_call = self . director . run (
task = f " History: { self . conversation . get_str ( ) } \n \n Task: { task } " ,
@ -391,6 +1032,7 @@ class HierarchicalSwarm:
except Exception as e :
error_msg = f " ❌ Failed to setup director: { str ( e ) } \n 🔍 Traceback: { traceback . format_exc ( ) } \n 🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues "
logger . error ( error_msg )
raise e
def step ( self , task : str , img : str = None , * args , * * kwargs ) :
"""
@ -417,9 +1059,13 @@ class HierarchicalSwarm:
try :
if self . verbose :
logger . info (
f " 👣 Executing single step for task: { task [ : 100 ] } ... "
f " 👣 Executing single step for task: { task } "
)
# Update dashboard for director execution
if self . interactive and self . dashboard :
self . dashboard . update_director_status ( " PLANNING " )
output = self . run_director ( task = task , img = img )
# Parse the orders
@ -430,6 +1076,20 @@ class HierarchicalSwarm:
f " 📋 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 )
# Convert orders to list of dicts for dashboard
orders_list = [
{
" agent_name " : order . agent_name ,
" task " : order . task ,
}
for order in orders
]
self . dashboard . update_director_orders ( orders_list )
self . dashboard . update_director_status ( " EXECUTING " )
# Execute the orders
outputs = self . execute_orders ( orders )
@ -450,7 +1110,13 @@ class HierarchicalSwarm:
error_msg = f " ❌ Failed to setup director: { str ( e ) } \n 🔍 Traceback: { traceback . format_exc ( ) } \n 🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues "
logger . error ( error_msg )
def run ( self , task : str , img : str = None , * args , * * kwargs ) :
def run (
self ,
task : Optional [ str ] = None ,
img : Optional [ str ] = None ,
* args ,
* * kwargs ,
) :
"""
Execute the hierarchical swarm for the specified number of feedback loops .
@ -462,7 +1128,8 @@ class HierarchicalSwarm:
context from previous iterations to subsequent ones .
Args :
task ( str ) : The initial task to be processed by the swarm .
task ( str , optional ) : The initial task to be processed by the swarm .
If None and interactive mode is enabled , will prompt for input .
img ( str , optional ) : Optional image input for the agents .
* args : Additional positional arguments .
* * kwargs : Additional keyword arguments .
@ -475,9 +1142,23 @@ class HierarchicalSwarm:
Exception : If swarm execution fails .
"""
try :
# Handle interactive mode task input
if task is None and self . interactive :
task = self . _get_interactive_task ( )
# if task is None:
# raise ValueError(
# "Task is required for swarm execution"
# )
current_loop = 0
last_output = None
# Start dashboard if in interactive mode
if self . interactive and self . dashboard :
self . dashboard . start ( self . max_loops )
self . dashboard . update_director_status ( " ACTIVE " )
if self . verbose :
logger . info (
f " 🚀 Starting hierarchical swarm run: { self . name } "
@ -492,6 +1173,13 @@ class HierarchicalSwarm:
f " 🔄 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 )
self . dashboard . update_director_status (
" PROCESSING "
)
# For the first loop, use the original task.
# For subsequent loops, use the feedback from the previous loop as context.
if current_loop == 0 :
@ -527,6 +1215,11 @@ class HierarchicalSwarm:
content = f " --- Loop { current_loop } / { self . max_loops } completed --- " ,
)
# Stop dashboard if in interactive mode
if self . interactive and self . dashboard :
self . dashboard . update_director_status ( " COMPLETED " )
self . dashboard . stop ( )
if self . verbose :
logger . success (
f " 🎉 Hierarchical swarm run completed: { self . name } "
@ -540,9 +1233,32 @@ class HierarchicalSwarm:
)
except Exception as e :
# Stop dashboard on error
if self . interactive and self . dashboard :
self . dashboard . update_director_status ( " ERROR " )
self . dashboard . stop ( )
error_msg = f " ❌ Failed to setup director: { str ( e ) } \n 🔍 Traceback: { traceback . format_exc ( ) } \n 🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues "
logger . error ( error_msg )
def _get_interactive_task ( self ) - > str :
"""
Get task input from user in interactive mode .
Returns :
str : The task input from the user
"""
if self . dashboard :
self . dashboard . console . print (
" \n [bold red]SWARMS CORPORATION[/bold red] - [bold white]TASK INPUT REQUIRED[/bold white] "
)
self . dashboard . console . print (
" [bold cyan]Enter your task for the hierarchical swarm:[/bold cyan] "
)
task = input ( " > " )
return task . strip ( )
def feedback_director ( self , outputs : list ) :
"""
Generate feedback from the director based on agent outputs .
@ -646,6 +1362,12 @@ class HierarchicalSwarm:
f " Agent ' { agent_name } ' not found in swarm. Available agents: { available_agents } "
)
# Update dashboard for agent execution
if self . interactive and self . dashboard :
self . dashboard . update_agent_status (
agent_name , " RUNNING " , task , " Executing task... "
)
output = agent . run (
task = f " History: { self . conversation . get_str ( ) } \n \n Task: { task } " ,
* args ,
@ -661,6 +1383,12 @@ class HierarchicalSwarm:
return output
except Exception as e :
# Update dashboard with error status
if self . interactive and self . dashboard :
self . dashboard . update_agent_status (
agent_name , " ERROR " , task , f " Error: { str ( e ) } "
)
error_msg = f " ❌ Failed to setup director: { str ( e ) } \n 🔍 Traceback: { traceback . format_exc ( ) } \n 🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues "
logger . error ( error_msg )
@ -805,8 +1533,9 @@ class HierarchicalSwarm:
)
except Exception as e :
error_msg = f " ❌ Failed to setup director : { str ( e ) } \n 🔍 Traceback: { traceback . format_exc ( ) } \n 🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues "
error_msg = f " ❌ Failed to parse orders : { str ( e ) } \n 🔍 Traceback: { traceback . format_exc ( ) } \n 🐛 If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues "
logger . error ( error_msg )
raise e
def execute_orders ( self , orders : list ) :
"""
@ -836,9 +1565,31 @@ class HierarchicalSwarm:
f " 📋 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 (
order . agent_name ,
" RUNNING " ,
order . task ,
" Processing... " ,
)
output = self . call_single_agent (
order . agent_name , order . task
)
# Update dashboard with completed status
if self . interactive and self . dashboard :
# Always show full output without truncation
output_display = str ( output )
self . dashboard . update_agent_status (
order . agent_name ,
" COMPLETED " ,
order . task ,
output_display ,
)
outputs . append ( output )
if self . verbose :