Overview
TheHierarchicalSwarm class implements a hierarchical architecture where a director agent distributes tasks to worker agents as structured orders. The director can provide feedback and iterate on results through multiple loops to achieve desired outcomes while maintaining conversation history throughout the process.
Each step prints a panel with the director’s orders, and its plan when the director returns one. Set print_on=False to hide it.
Class Definition
Parameters
str
default:"HierarchicalAgentSwarm"
The name identifier for this swarm instance
str
default:"Distributed task swarm"
A description of the swarm’s purpose and capabilities
Optional[Union[Agent, Callable, Any]]
default:"None"
The director agent that coordinates the swarm. If None, a default director is created that returns an
OrderBatch through a function call. A custom director must return output that parse_orders() can read: an OrderBatch or SwarmSpec, a JSON string or dict with an orders key, or a tool call carrying one. See Custom directorAgentListType
default:"None"
List of worker agents available for task execution. Must not be empty. Nested orchestrators work too; they are matched by their
nameint
default:"1"
Maximum number of feedback loops the swarm can perform (must be > 0)
OutputType
default:"dict-all-except-first"
Format for the final output of the swarm
str
default:"gpt-5.4"
Model for the separate agent that writes director feedback when
director_feedback_on=Truestr
default:"Director"
Name identifier for the director agent
str
default:"gpt-5.4"
Model name for the main director agent
bool
default:"True"
Forwarded to the helper that adds the worker roster to the shared conversation. The roster is added before the collaboration prompt would be appended, so this flag currently has no effect
bool
default:"False"
Whether director feedback is enabled. Feedback runs only when
max_loops > 1, never on the final loop, and not when agent_as_judge=Truebool
default:"False"
When
True, run() called without a task prompts for one on the console, and every worker’s print_on is set to False at constructionstr
default:"HIEARCHICAL_SWARM_SYSTEM_PROMPT"
Custom system prompt for the director agent
bool
default:"False"
Enable enhanced multi-agent collaboration prompts for worker agents
float
default:"0.7"
Temperature parameter for director agent’s LLM
float
default:"0.9"
Top-p parameter for director agent’s LLM
The auto-created director sends both
director_temperature and director_top_p. Anthropic’s current models reject the two together, so for a Claude director set one of them to None, for example director_settings={"model_name": "claude-sonnet-4-6", "top_p": None}.bool
default:"False"
Whether to run a separate planning pass before the director writes orders. The plan is recorded in the shared conversation under the director’s name
bool
default:"False"
Whether to enable autosaving of conversation history to workspace directory
bool
default:"False"
Log the autosave directory and each save. It does not control the orders panel; see
print_onbool
default:"True"
When
True, worker agents assigned in a single director order are executed concurrently; when False, they run one after another.int
default:"None"
Thread pool size used when
parallel_execution is True. Defaults to 95% of available CPU cores. Must be greater than zero if provided.bool
default:"False"
When
True, a judge agent scores the worker outputs after each step and returns a JudgeReport. It replaces director feedback, and its report becomes the previous-loop result the next loop builds on.str
default:"gpt-5.4"
Model used by the judge agent when
agent_as_judge=True.Optional[Dict[str, Any]]
default:"None"
Additional
Agent constructor settings for the automatically created director. Values in this dictionary override the legacy director parameters. Use planning_system_prompt to customize the optional planning pass. The swarm always forces the director’s output_type to "final".int
default:"1"
Number of retry attempts after a worker’s initial execution fails. After all attempts are exhausted, the worker is marked unavailable in the shared conversation and its failure is reported to the director. Must be greater than or equal to
0.int
default:"1"
Maximum number of recovery rounds in which the director can reassign failed tasks to healthy workers. The swarm continues running when recovery cannot complete a task. Must be greater than or equal to
0.bool
default:"True"
Whether to print the director’s orders, and its plan when it returns one, to the console at each step. Orders are shown in full, and the panel is titled with the director’s name. This is separate from
verbose, which controls loggingHierarchicalSwarm forces every configurable director and worker agent to use output_type="final". The swarm-level output_type parameter still controls the format returned by HierarchicalSwarm.run().Methods
run()
str
The initial task to be processed by the swarm. If None and interactive mode is enabled, will prompt for input
str
Optional image input for the agents
Any
The formatted conversation history as output, formatted according to output_type configuration
- Clears the conversation and every agent’s delivery cursor, then re-adds the worker roster and the task, so each call starts clean
- Director distributes orders to agents (after an optional planning pass)
- Agents execute tasks and report back to director
- Failed workers are retried up to
max_agent_retries - Exhausted workers are marked unavailable in shared context
- Director reassigns failed tasks to healthy workers, up to
max_reassignment_attempts - Director evaluates results and issues new orders if needed (up to
max_loops). Each later loop gets the previous loop’s result and the original task - Records a
--- Loop N/M completed ---or--- Loop N/M failed: <error> ---marker after every loop - Returns final output formatted per swarm-level
output_type, and saves the conversation whenautosave=True
step()
str
required
The task to be processed in this step
str
Optional image input for the task
bool
default:"False"
Skips director feedback, which could not inform another loop
Any
The results from this step: the judge report when
agent_as_judge=True, director feedback when it runs, otherwise the list of worker outputs. An empty list when the director issued no orders- Director runs (after the planning pass, if enabled) and returns orders
parse_orders()extracts the plan and orders; the panel prints them whenprint_on=True- Agents execute assigned tasks
- Optional judge scoring or director feedback on results
step() raises and run() records the loop as failed.
parse_orders()
(plan, orders) tuple, where orders is a list of HierarchicalOrder. Accepts an OrderBatch, a SwarmSpec, a JSON string (decoded twice if double-encoded), a dict, an OpenAI-style tool call, or a list of tool calls or conversation turns. plan is None unless the output carries one. Raises ValueError when no orders can be found. The logic lives in swarms/structs/hierarchical_order_parser.py.
batched_run()
run() once per task via the shared batch utility.
Parameters:
List[str]
required
Tasks to execute
Optional[Union[str, List[Optional[str]]]]
One image applied to every task, or one image per task
Optional[List[Optional[str]]]
Images paired with tasks
Optional[int]
default:"None"
Concurrent task limit;
None runs tasks sequentiallybool
default:"False"
Return results keyed by task instead of as a list
bool
default:"False"
Return exceptions instead of raising them
list | dict
Results in task order, or keyed by task when
return_agent_output_dict=Truerun() resets both.
display_hierarchy()
reliability_checks()
- At least one agent is provided
- max_loops is greater than 0
- max_agent_retries is greater than or equal to 0
- max_reassignment_attempts is greater than or equal to 0
- max_workers is greater than 0 when provided
- Director is available (creates default if needed)
ValueError: If swarm configuration is invalid
Data Models
The schemas live inswarms.schemas.hs_schemas. SwarmSpec is also importable from swarms.structs.hiearchical_swarm.
HierarchicalOrder
OrderBatch
The schema the default director returns.SwarmSpec
The legacy schema with a plan. A custom director can still return it; the plan is then shown in the orders panel.JudgeReport
Used whenagent_as_judge=True. A one-shot judge agent scores each worker agent’s output instead of the director issuing free-form feedback.
Usage Example
Conversation Autosave
Whenautosave=True, the directory is created at construction and the conversation history is saved at the end of every run(), including a failed one:
$WORKSPACE_DIR/swarms/HierarchicalSwarm/{swarm-name}-{timestamp}/conversation_history.json
WORKSPACE_DIR defaults to ./agent_workspace. Each run overwrites the same file.
This enables:
- Post-execution analysis
- Debugging and monitoring
- Historical tracking of swarm operations