@ -51,6 +57,7 @@ from swarms.utils.history_output_formatter import (
history_output_formatter,
history_output_formatter,
)
)
fromswarms.utils.output_typesimportOutputType
fromswarms.utils.output_typesimportOutputType
fromswarms.utils.formatterimportformatter
classHierarchicalSwarmDashboard:
classHierarchicalSwarmDashboard:
@ -612,6 +619,13 @@ class SwarmSpec(BaseModel):
individualagentswithintheswarm.
individualagentswithintheswarm.
"""
"""
# # 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(
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. "
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(
returnAgent(
agent_name=self.director_name,
agent_name=self.director_name,
agent_description="A director agent that can create a plan and distribute orders to agents",
agent_description="A director agent that can create a plan and distribute orders to agents",
system_prompt=self.director_system_prompt,
system_prompt=self.director_system_prompt,
model_name=self.director_model_name,
model_name=self.director_model_name,
temperature=self.director_temperature,
top_p=self.director_top_p,
max_loops=1,
max_loops=1,
base_model=SwarmSpec,
base_model=SwarmSpec,
tools_list_dictionary=[schema],
tools_list_dictionary=[schema],
@ -854,34 +948,8 @@ class HierarchicalSwarm:
)
)
exceptExceptionase:
exceptExceptionase:
error_msg=f"[ERROR] Failed to setup director: {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(
logger.error(error_msg)
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):
defreliability_checks(self):
"""
"""
@ -896,6 +964,11 @@ class HierarchicalSwarm:
ValueError:Iftheswarmconfigurationisinvalid.
ValueError:Iftheswarmconfigurationisinvalid.
"""
"""
try:
try:
ifself.verbose:
logger.info(
f"Hiearchical Swarm: {self.name} Reliability checks in progress..."
)
ifnotself.agentsorlen(self.agents)==0:
ifnotself.agentsorlen(self.agents)==0:
raiseValueError(
raiseValueError(
"No agents found in the swarm. At least one agent must be provided to create a hierarchical swarm."
"No agents found in the swarm. At least one agent must be provided to create a hierarchical swarm."
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
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"
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,
img=img,
)
)
self.conversation.add(
role=self.director.agent_name,content=out
task+=plan
ifself.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
# Run the director with the context
function_call=self.director.run(
function_call=self.director.run(
@ -962,13 +1048,19 @@ class HierarchicalSwarm:
role="Director",content=function_call
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
returnfunction_call
exceptExceptionase:
exceptExceptionase:
error_msg=f"[ERROR] Failed to run director: {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(
logger.error(error_msg)
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
raisee
defstep(
defstep(
@ -1006,6 +1098,11 @@ class HierarchicalSwarm:
Exception:Ifstepexecutionfails.
Exception:Ifstepexecutionfails.
"""
"""
try:
try:
ifself.verbose:
logger.info(
f"[STEP] Executing single step for task: {task}"
)
# Update dashboard for director execution
# Update dashboard for director execution
ifself.interactiveandself.dashboard:
ifself.interactiveandself.dashboard:
self.dashboard.update_director_status("PLANNING")
self.dashboard.update_director_status("PLANNING")
@ -1015,6 +1112,11 @@ class HierarchicalSwarm:
# Parse the orders
# Parse the orders
plan,orders=self.parse_orders(output)
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
# 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"
logger.error(
logger.error(error_msg)
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"{error_msg}\n[TRACE] Traceback: {traceback.format_exc()}\n[BUG] If this issue persists, please report it at: https://github.com/kyegomez/swarms/issues"
)
)
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"
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(
logger.error(error_msg)
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:
def_get_interactive_task(self)->str:
"""
"""
@ -1200,6 +1328,9 @@ class HierarchicalSwarm:
Exception:Iffeedbackgenerationfails.
Exception:Iffeedbackgenerationfails.
"""
"""
try:
try:
ifself.verbose:
logger.info("[FEEDBACK] Generating director feedback")
"[SUCCESS] Director feedback generated successfully"
)
returnoutput
returnoutput
exceptExceptionase:
exceptExceptionase:
error_msg=f"[ERROR] Feedback director failed: {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(
logger.error(error_msg)
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"
f"[ERROR] Failed to call agent {agent_name}: {str(e)}"
logger.error(error_msg)
)
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
# Handle different output formats from the director
@ -1406,8 +1548,19 @@ class HierarchicalSwarm:
]
]
]
]
ifself.verbose:
logger.success(
f"[SUCCESS] Successfully parsed plan and {len(orders)} orders"
)
returnplan,orders
returnplan,orders
exceptjson.JSONDecodeError:
except(
json.JSONDecodeError
)asjson_err:
ifself.verbose:
logger.warning(
f"[WARN] JSON decode error: {json_err}"
)
pass
pass
# Check if it's a direct function call format
# Check if it's a direct function call format
elif"function"initem:
elif"function"initem:
@ -1429,8 +1582,19 @@ class HierarchicalSwarm:
]
]
]
]
ifself.verbose:
logger.success(
f"[SUCCESS] Successfully parsed plan and {len(orders)} orders"
)
returnplan,orders
returnplan,orders
exceptjson.JSONDecodeError:
except(
json.JSONDecodeError
)asjson_err:
ifself.verbose:
logger.warning(
f"[WARN] JSON decode error: {json_err}"
)
pass
pass
# If no function call found, raise error
# If no function call found, raise error
raiseValueError(
raiseValueError(
@ -1445,6 +1609,11 @@ class HierarchicalSwarm:
fororderinoutput["orders"]
fororderinoutput["orders"]
]
]
ifself.verbose:
logger.success(
f"[SUCCESS] Successfully parsed plan and {len(orders)} orders"
)
returnplan,orders
returnplan,orders
else:
else:
raiseValueError(
raiseValueError(
@ -1456,10 +1625,8 @@ class HierarchicalSwarm:
)
)
exceptExceptionase:
exceptExceptionase:
error_msg=f"[ERROR] Failed to parse orders: {str(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(
logger.error(error_msg)
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
# Update dashboard for agent execution
ifself.interactiveandself.dashboard:
ifself.interactiveandself.dashboard:
self.dashboard.update_agent_status(
self.dashboard.update_agent_status(
@ -1520,21 +1695,15 @@ class HierarchicalSwarm:
outputs.append(output)
outputs.append(output)
ifself.verbose:
logger.success(
f"[SUCCESS] All {len(orders)} orders executed successfully"
)
returnoutputs
returnoutputs
exceptExceptionase:
exceptExceptionase:
error_msg=(
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
# Initialize a list to store the results
results=[]
results=[]
@ -1584,10 +1761,20 @@ class HierarchicalSwarm:
)
)
results.append(result)
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
returnresults
exceptExceptionase:
exceptExceptionase:
error_msg=f"[ERROR] Batched hierarchical swarm run failed: {str(e)}"
error_msg=f"[ERROR] Batched hierarchical swarm run failed: {str(e)}"
ifself.verbose:
logger.error(error_msg)
logger.error(
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"