HierarchicalSwarm implements a director-worker pattern. A central director agent analyzes the task, produces a structured plan (a SwarmSpec), distributes orders to specialist worker agents, and — optionally — provides feedback or runs a judge over the outputs to iterate further.
When to Use
- Complex project management — multi-stage projects with specialized roles
- Team coordination — coordinating diverse specialist agents
- Quality control — iterative refinement through feedback loops
- Hierarchical decisions — tasks requiring oversight and delegation
- Strategic planning — breaking down complex goals into specialized subtasks
Key Features
- Automatic director agent creation (or pass your own)
- Structured output via
SwarmSpec(Pydantic schema withplan+orders) - Multi-loop feedback and refinement
- Optional agent-as-judge phase for objective scoring
- Optional planning phase before order generation
- Optional team-awareness preamble for workers
- Parallel order execution (default)
- Interactive
richdashboard mode - Conversation history tracking
- Autosave of conversation history to a workspace directory
Basic Example
Architecture Flow
SwarmSpec Structure
The director outputs a Pydantic-validated plan:Key Parameters
str
default:"HierarchicalAgentSwarm"
Name for the swarm instance.
str
default:"Distributed task swarm"
Description of the swarm’s purpose.
List[Agent]
required
Specialist worker agents.
Agent
Custom director agent. If
None, a default director is created using director_model_name + director_system_prompt.int
default:"1"
Maximum number of plan → execute → feedback iterations.
OutputType
default:"dict-all-except-first"
Format of the returned conversation history.
str
default:"Director"
Display name for the director agent.
str
default:"gpt-5.4"
Model used by the director.
str
default:"HIEARCHICAL_SWARM_SYSTEM_PROMPT"
System prompt for the director. Override to customize director behavior.
float
default:"0.7"
Sampling temperature for the director.
float
default:"0.9"
Top-p for the director.
str
default:"gpt-5.4"
Model used when the director generates feedback on worker outputs.
bool
default:"True"
Enable director feedback after each loop.
bool
default:"True"
Run an explicit planning pass before generating orders.
bool
default:"False"
Run a judge agent that scores worker outputs against the plan.
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. These values override the legacy director parameters. Set planning_system_prompt in this dictionary to customize the optional planning pass.int
default:"1"
Number of retries after a worker’s initial execution fails. When retries are exhausted, the worker is marked unavailable in the shared swarm conversation.
int
default:"1"
Maximum number of recovery rounds in which the director can move failed tasks to healthy workers. A failed task does not stop successful workers or abort the swarm.
bool
default:"True"
Inject the multi-agent collaboration preamble into agents.
bool
default:"False"
Augment every worker’s system prompt with team awareness (other agents + roles).
bool
default:"True"
Execute multi-agent orders concurrently within a loop.
bool
default:"False"
Enable the interactive
rich dashboard.bool
default:"True"
Persist conversation history to a workspace directory.
bool
default:"False"
Enable info-level logging.
The swarm enforces
output_type="final" on all configurable director and worker agents so only final responses pass between agents. The swarm-level output_type still determines the value returned from run().Methods
run(task, img=None)
Execute the swarm end-to-end.
batched_run(tasks, ...)
Run the swarm sequentially over a batch of tasks.
run_stream(task, ...)
Stream output tokens as they arrive from the director and workers. Useful for live UI.
display_hierarchy()
Visualize the swarm’s tree with rich.Tree.
feedback_director(outputs)
Manually trigger the feedback director on a list of worker outputs.
run_judge_agent(outputs)
Manually score worker outputs with the judge agent (requires agent_as_judge=True).
Advanced Configuration
Custom Director
Planning + Multiple Loops
planning_enabled=True:
- Director runs a planning pass first
- The plan is added to the conversation context
- Director then emits concrete orders
- Workers execute with full plan context
Agent-as-Judge
AgentScore / JudgeReport Pydantic object summarizing per-agent quality, which feeds the next loop’s director.
Team-Awareness Preamble
system_prompt is extended with a description of every other team member so workers can write coherent hand-offs.
Interactive Dashboard
- Swarm metadata (name, description, loops)
- Director status and current plan
- Per-agent status matrix with loop tracking
- Real-time progress updates
Autosave
$WORKSPACE_DIR/swarms/HierarchicalSwarm/{name}-{timestamp}/.
If WORKSPACE_DIR is unset it defaults to ./agent_workspace.
Use Cases
Software Development Team
Research Team
Marketing Campaign
Multi-Loop Refinement
Withmax_loops > 1, the director can refine outputs across iterations:
- Director creates a new plan informed by previous results
- Director issues orders (possibly to different agents or with different tasks)
- Workers execute
- Results — and any feedback/judge output — are appended to the conversation
- The next loop sees the complete context
Order Execution
Concurrent Execution (default)
Orders for multiple agents run in parallel via aThreadPoolExecutor (execute_orders), one worker thread per order:
Sequential Execution
Setparallel_execution=False to run orders one after another within a loop. Useful when each order depends on the previous one’s output.
Director System Prompt
The defaultHIEARCHICAL_SWARM_SYSTEM_PROMPT instructs the director to:
- Analyze the task
- Identify required expertise
- Create a comprehensive plan
- Distribute work appropriately
- Evaluate results
- Provide constructive feedback
Best Practices
Loop count: start at 1 loop for simple coordination; 2–3 for quality refinement. Avoid >3 unless you’re seeing clear improvement per loop.
- Specialized workers — each agent should have an obviously different area of expertise; overlapping workers waste tokens.
- Director model — use a stronger model than the workers (e.g. Claude Sonnet, GPT-5.4). The director’s planning quality bounds the whole swarm.
- Loop balance — every extra loop costs an additional director pass + every worker run. Budget accordingly.
- Planning phase — enable for complex tasks that benefit from a strategy step.
- Judge phase — enable when output quality is uneven and you want explicit scoring/feedback.
- Dashboard — useful for demos and debugging.
Error Handling
reliability_checks() runs at construction and validates:
- At least one agent is provided
max_loops > 0- Director agent can be created or is already valid
Performance Considerations
Parallel Order Execution
execute_orders runs all orders for a loop simultaneously when parallel_execution=True, submitting each order to a ThreadPoolExecutor:
Conversation Context
The full conversation flows through every loop, giving the director complete state:Related Architectures
- Heavy Swarm — fixed multi-phase analysis with question generation
- Mixture of Agents — parallel experts + aggregator
- Agent Rearrange — custom flows without a director
- Sequential Workflow — simple linear flows
- Structures Catalog — full enumeration of every multi-agent structure