Skip to main content
The HierarchicalSwarm implements a director-worker pattern. A central director agent analyzes the task, returns structured orders (an OrderBatch) for 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 orders via OrderBatch (Pydantic schema of agent_name + task pairs)
  • A console panel of the director’s orders, and its plan when it returns one, at every step
  • 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)
  • Worker retries, and director reassignment of failed tasks
  • Conversation history tracking, reset at the start of every run
  • Autosave of conversation history to a workspace directory

Basic Example

Architecture Flow

Order structure

The default director returns its orders through a function call that matches OrderBatch. The schemas live in swarms.schemas.hs_schemas:
Example output:
SwarmSpec is the older shape with a plan. A custom director can still return it, and the plan then appears above the orders in the console panel. parse_orders() accepts either shape, as a model, JSON string, dict or tool call.

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. A custom director must return orders; see Custom director.
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 for the separate agent that writes feedback on worker outputs.
bool
default:"False"
Enable director feedback after each loop except the last. Has no effect when max_loops=1 or agent_as_judge=True.
bool
default:"False"
Run an explicit planning pass before generating orders.
bool
default:"False"
Run a judge agent that scores worker outputs after each step. Replaces director feedback.
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"
Forwarded to the roster helper that seeds the shared conversation. The roster is added to the conversation before the collaboration prompt would be appended, so this flag currently has no effect.
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.
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"
Prompt for a task on the console when run() is called without one. Also turns off every worker’s print_on.
bool
default:"True"
Print the director’s orders, and its plan when it returns one, in a panel at every step.
bool
default:"False"
Persist conversation history to a workspace directory.
bool
default:"False"
Log the autosave directory and each save.
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. Each task starts from an empty conversation and fresh delivery cursors, so one task’s messages never leak into the next.

display_hierarchy()

Visualize the swarm’s tree with rich.Tree.

feedback_director(outputs)

Manually trigger the feedback director on a list of worker outputs. It reviews the latest worker messages in the conversation and records its feedback under the director’s name.

run_judge_agent(outputs)

Manually score the conversation with the judge agent. It works whether or not agent_as_judge is set; the flag only decides whether step() calls it. outputs is returned as a string if the judge fails.

parse_orders(output)

Extract (plan, orders) from a director response. plan is None for an OrderBatch. Raises ValueError when the output carries no orders.

Advanced Configuration

Custom director

To change the auto-created director’s name, model or prompt, use director_settings. It keeps the OrderBatch function schema the swarm needs:
The auto-created director sends both director_temperature (0.7) and director_top_p (0.9). Anthropic’s current models reject the two together, so set one to None for a Claude director, as above.
A director you pass yourself must return orders that parse_orders() can read: an OrderBatch or SwarmSpec, JSON or a dict with an orders key, or a tool call carrying one. A plain-text director fails every loop, and run() then raises. This director returns a SwarmSpec, so its plan shows in the panel:

Planning + Multiple Loops

With planning_enabled=True:
  1. A planning agent, using DIRECTOR_PLANNING_PROMPT or director_settings["planning_system_prompt"], writes a text plan without orders
  2. The plan is added to the conversation under the director’s name
  3. Director then emits concrete orders
  4. Workers whose run() accepts messages see the plan in their message history
The director’s history excludes messages recorded under its own name, so the plan reaches the workers but not the order-writing director.

Agent-as-Judge

When enabled, after worker outputs are gathered the judge agent reads the conversation and returns a structured JudgeReport: an overall 0-10 score, an AgentScore per worker and a summary. The report is added to the conversation and passed to the next loop as the previous result. Director feedback is skipped while the judge is on.

Team-Awareness Preamble

Each worker’s system_prompt is extended with a description of every other team member so workers can write coherent hand-offs.

Orders panel and interactive mode

With the default print_on=True, every step prints a panel titled with the director’s name. It lists each order in full as agent - task, under the director’s plan when the director returns one. Set print_on=False to hide it.
interactive=True does not open a dashboard. It reads the task from the console when run() gets none, and silences the workers’ own printing.

Autosave

When enabled, the swarm writes conversation_history.json under $WORKSPACE_DIR/swarms/HierarchicalSwarm/{name}-{timestamp}/. If WORKSPACE_DIR is unset it defaults to ./agent_workspace. The directory is created once, at construction, and the file is rewritten at the end of every run.

Use Cases

Software Development Team

Research Team

Marketing Campaign

Multi-Loop Refinement

With max_loops > 1, the director can refine outputs across iterations:
Each loop:
  1. From the second loop on, the director’s task is the previous loop’s result plus the original task
  2. Director issues orders (possibly to different agents or with different tasks)
  3. Workers execute
  4. Results — and any feedback/judge output — are appended to the conversation, followed by a --- Loop N/M completed --- marker
  5. The next loop’s director receives the messages it has not seen yet
A loop that raises is marked --- Loop N/M failed: <error> ---, and the next loop still runs.

Order Execution

Concurrent Execution (default)

Orders for multiple agents run in parallel on a thread pool sized by max_workers (execute_orders). Outputs are added to the conversation in order sequence once every order has finished:

Sequential Execution

Set parallel_execution=False to run orders one after another within a loop. Each output is added to the conversation as soon as it finishes, so later workers see earlier ones. Useful when each order depends on the previous one’s output.

Director System Prompt

The default HIEARCHICAL_SWARM_SYSTEM_PROMPT, in swarms.prompts.hierarchical_swarm_prompts, instructs the director to:
  • Review the swarm’s goals
  • Decompose the task into granular subtasks
  • Match each subtask to the best-suited agent
  • Write one clear HierarchicalOrder per task
  • Return only an OrderBatch, with no plan or other top-level fields
You can fully override it. The auto-created director keeps the OrderBatch function schema whatever the prompt says:

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.
  1. Specialized workers — each agent should have an obviously different area of expertise; overlapping workers waste tokens.
  2. 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.
  3. Loop balance — every extra loop costs an additional director pass + every worker run. Budget accordingly.
  4. Planning phase — enable for complex tasks that benefit from a strategy step.
  5. Judge phase — enable when output quality is uneven and you want explicit scoring/feedback.
  6. Orders panel — keep print_on=True while developing to see every delegation; turn it off when the console output is noise.
Each loop runs the director and every selected worker. Costs grow roughly linearly with max_loops × len(agents).

Error Handling

Configuration errors raise ValueError when you construct the swarm, not when you run it:
reliability_checks() runs at construction and validates:
  • At least one agent is provided
  • max_loops > 0
  • max_agent_retries >= 0 and max_reassignment_attempts >= 0
  • max_workers > 0
  • Director agent can be created or is already valid
At run time, a failing worker is retried, then marked unavailable and reassigned; the swarm records it in the conversation and keeps going. A failing loop is recorded and the next loop runs. run() raises only when every loop fails:

Performance Considerations

Parallel Order Execution

execute_orders runs all orders for a loop simultaneously when parallel_execution=True. Each order goes to a thread pool of max_workers threads (95% of CPU cores by default) and runs with its own retries.

Conversation context

Each agent gets only what it needs from the shared conversation:
  • Director — "History: {new messages} \n\n Task: {task}", where the history holds only the messages it has not been given yet, tracked by a per-agent delivery cursor. The first call includes the worker roster.
  • Workers — their order as the task, plus the conversation as typed chat turns when their run() accepts messages. The roster is left out.
  • Judge — the conversation as typed chat turns.
  • Feedback director — the current step’s worker responses only.
run() resets the conversation and the cursors, so every task starts clean.