Overview
TheHierarchicalSwarm class implements a hierarchical architecture where a director agent creates plans and distributes tasks to worker agents. The director can provide feedback and iterate on results through multiple loops to achieve desired outcomes while maintaining conversation history throughout the process.
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 will be created
AgentListType
default:"None"
List of worker agents available for task execution. Must not be empty
int
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 name for the feedback director
str
default:"Director"
Name identifier for the director agent
str
default:"gpt-5.4"
Model name for the main director agent
bool
default:"True"
Whether to add collaboration prompts to agents
bool
default:"True"
Whether director feedback is enabled
bool
default:"False"
Enable interactive dashboard with real-time monitoring
str
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
bool
default:"True"
Whether to enable the planning phase before order distribution
bool
default:"True"
Whether to enable autosaving of conversation history to workspace directory
bool
default:"False"
Enable verbose logging output
bool
default:"True"
When
True, worker agents assigned in a single director order are executed concurrently; when False, they run one after another.bool
default:"False"
When
True, a judge agent evaluates the worker outputs to inform the director’s feedback loop.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.HierarchicalSwarm 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
Callable[[str, str, bool], None]
Callback function for streaming agent outputs. Parameters are (agent_name, chunk, is_final)
Any
The formatted conversation history as output, formatted according to output_type configuration
- Director creates a plan and distributes orders to agents
- 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) - All context and conversation history is preserved throughout
- Returns final output formatted per swarm-level
output_type
step()
str
required
The task to be processed in this step
str
Optional image input for the task
Callable
Callback for streaming outputs
Any
The results from this step, either agent outputs or director feedback
- Director runs to create plan and orders
- Orders are parsed and distributed
- Agents execute assigned tasks
- Optional director feedback on results
arun()
run() in asyncio.to_thread(). Accepts the same parameters as run() and returns the same result.
batched_run()
run() once per task and returning a list of results (one per task).
arun_stream()
with_events=False (default) it yields (agent_name, token) tuples; when True it yields structured event dicts tagged with role (director / worker / aggregator / swarm) and loop index, with event types swarm_start, director_start, token, director_end, worker_start, worker_end, aggregator_start, aggregator_end, swarm_end.
run_stream()
arun_stream(). Bridges the async generator to a sync iterator using a background thread. Use arun_stream() directly when already inside a running event loop (e.g. a FastAPI handler).
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
- Director is available (creates default if needed)
ValueError: If swarm configuration is invalid
Data Models
HierarchicalOrder
SwarmSpec
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.
Interactive Dashboard
Wheninteractive=True, the HierarchicalSwarm displays a real-time dashboard with:
- Operations Status: Swarm name, description, current loop, agent count
- Director Operations: Current plan and active orders
- Agent Monitoring Matrix: Real-time agent status, tasks, and outputs
- Progress Tracking: Loop completion and runtime metrics
Usage Example
Conversation Autosave
Whenautosave=True, conversation history is automatically saved to:
workspace_dir/swarms/HierarchicalSwarm/{swarm-name}-{timestamp}/conversation_history.json
This enables:
- Post-execution analysis
- Debugging and monitoring
- Historical tracking of swarm operations