Skip to main content

Overview

The AutoSwarmBuilder class automatically builds and manages swarms of AI agents by intelligently decomposing tasks and creating specialized agents as needed. It uses a sophisticated boss agent system to delegate work, design agent architectures, and orchestrate multi-agent collaboration. The boss agent’s reply is parsed and validated against a Pydantic schema. Malformed JSON or a schema mismatch triggers a repair retry that feeds the error back to the model; if no valid reply arrives within the budget, a ValueError is raised. Each run() is recorded as an AutoSwarmBuilder.run trace span when telemetry is enabled. When the swarm is executed, the SwarmRouter.run span nests under it, so the build phase and the delegated run share one trace. See Telemetry.

Class Definition

Parameters

str
default:"auto-swarm-builder"
The name of the swarm builder instance
str
default:"Auto Swarm Builder"
A description of the swarm builder’s purpose
bool
default:"True"
Stored as builder.verbose but not read. The builder logs through loguru either way
int
default:"1"
Passed as max_loops to the SwarmRouter built by build_and_run_swarm() and initialize_swarm_router(). Cannot be 0
str
default:"gpt-5.4"
The LLM model to use for the boss agent that designs the swarm architecture
int
default:"8000"
Maximum tokens for the LLM responses from the boss agent
str
default:"return-agents"
Type of execution to perform. Options: “return-agents”, “return-swarm-router-config”, “return-agents-objects”
str
default:"BOSS_SYSTEM_PROMPT"
System prompt for the boss agent that designs swarm architectures. Defaults to comprehensive agent design prompt
dict
default:"{}"
Additional arguments to pass to the LiteLLM wrapper
bool
default:"False"
Default value for run()’s execute parameter. When True, run() builds real Agent objects from a freshly generated spec and executes them through a SwarmRouter (via build_and_run_swarm()) instead of returning a spec-only result

Attributes you can set after construction

These are not constructor arguments. Set them on the instance before calling run().
Optional[int]
default:"None"
Upper bound on how many agents the boss agent may generate. A larger roster raises ValueError. Unbounded when None
int
default:"1"
Number of repair retries when the boss agent’s reply is malformed JSON or fails schema validation

Execution Types

return-agents

Returns agent specifications as a dictionary:

return-swarm-router-config

Returns complete SwarmRouter configuration:

return-agents-objects

Returns instantiated Agent objects ready for use:

Methods

run()

Runs the swarm builder on a given task, creating agents based on execution type. Parameters:
str
required
The task to execute. The boss agent will analyze this task and design an appropriate swarm architecture
Optional[bool]
default:"None"
When True, builds real agents and a SwarmRouter from a freshly generated spec and runs it (see build_and_run_swarm()), returning a dict that includes the execution output. When False, only a spec-only result is returned, per swarm_type. Defaults to self.auto_execute when left as None
Returns:
Any
When executing (execute resolves to True): a dict from build_and_run_swarm(). Otherwise, the result depends on swarm_type:
  • “return-agents”: Dictionary with agent specifications
  • “return-swarm-router-config”: SwarmRouter configuration dictionary
  • “return-agents-objects”: List of instantiated Agent objects
Raises:
  • ValueError: If swarm_type is invalid, or if the generated spec fails validation (see create_agents())
  • Exception: If there’s an error during swarm execution

build_and_run_swarm()

Designs a multi-agent team for task and executes it. Generates one validated SwarmRouterConfig, builds the real Agent objects from that same spec’s agents, and runs a SwarmRouter with them — so the agents that execute are exactly the ones described in the returned metadata, unlike chaining create_agents() and initialize_swarm_router() (which make two independent, potentially-disagreeing LLM calls). This is what run() calls when execute resolves to True. Parameters:
str
required
The task to design and run a swarm for
Returns:
dict
{"name", "description", "agents" (names actually built), "swarm_type", "task", "output"} where output is the SwarmRouter’s execution result
The router is built with output_type="dict" and the builder’s max_loops. The spec’s rules and multi_agent_collab_prompt fields are not applied to the agents.

create_agents()

Creates agent specifications for a given task using the boss agent. Parameters:
str
required
The task to create agents for
Returns:
dict
{"agents": [...]}, one validated AgentSpec dict per agent
Raises:
  • ValueError: If no valid reply arrives within the repair budget, if two agents share an agent_name, or if the roster exceeds max_agents

create_agents_from_specs()

Creates Agent objects from agent specifications. Parameters:
Any
required
Dictionary or Pydantic model containing agent specifications
Returns:
List[Agent]
List of instantiated Agent objects ready for use
Note: Automatically handles parameter name mapping (e.g., ‘description’ → ‘agent_description’) Raises: ValueError if two specs share a non-empty agent_name.

create_router_config()

Creates a SwarmRouter configuration for a given task. Parameters:
str
required
The task to create router configuration for
Returns:
dict
The SwarmRouterConfig fields as a dict. task is set to the exact string you passed, not the model’s echo of it
Raises:
  • ValueError: If the reply fails validation, names a swarm_type outside SwarmType, repeats an agent_name, or exceeds max_agents

batch_run()

Runs the swarm builder on a list of tasks sequentially. Each task goes through run(), so each gets its own trace span. Parameters:
List[str]
required
List of tasks to execute
Returns:
List[Any]
List of results from each task execution

reliability_check()

Performs reliability checks on the AutoSwarmBuilder configuration. Raises:
  • ValueError: If max_loops is 0, max_agents is set and not positive, or max_json_repair_attempts is negative
Called once from __init__. Call it again yourself if you change max_agents or max_json_repair_attempts afterwards and want them checked.

list_types()

Lists all available execution types. Returns:
List[str]
List of available execution types

initialize_swarm_router()

Runs agents you already have under an architecture the boss agent picks. The boss generates a SwarmRouterConfig for the task; only its name, description, swarm_type, and rearrange_flow are used, and the generated agent specs are discarded. The SwarmRouter is built with your agents, the builder’s max_loops, and output_type="dict". Not called by run(). To design the agents and run them from one consistent spec, use build_and_run_swarm() instead. Parameters:
List[Agent]
required
Agents to pass to the constructed SwarmRouter
str
required
The task used to derive the SwarmRouter configuration and to execute
Returns: Result of swarm_router.run(task) Raises: Exception if router config generation or execution fails

dict_to_agent()

Builds Agent objects from a raw {"agents": [...]} dictionary by delegating to create_agents_from_specs(), so the description → agent_description mapping and the duplicate-name check apply. Any non-dict input returns an empty list. Parameters:
dict
required
Dictionary containing an "agents" list of agent configuration dicts
Returns: List[Agent]

Data Models

AgentSpec

SwarmRouterConfig

This SwarmRouterConfig lives in swarms.structs.auto_swarm_builder and is the boss agent’s output schema. It is a different class from the SwarmRouterConfig in swarms.structs.swarm_router. The generated swarm_type must be a SwarmType member. "AutoSwarmBuilder" and "auto" are always rejected so a generated spec cannot recurse.

Boss Agent Design Principles

The AutoSwarmBuilder uses a sophisticated boss agent with expertise in:
  1. Comprehensive Task Analysis: Deconstructing tasks into components and sub-tasks
  2. Agent Design Excellence: Creating agents with clear purposes and complementary personalities
  3. System Prompt Engineering: Crafting detailed prompts with role, capabilities, and protocols
  4. Multi-Agent Coordination: Designing communication channels and task handoff procedures
  5. Quality Assurance: Establishing success criteria and validation procedures

Usage Examples

Basic Agent Creation

Create Agent Objects

Generate SwarmRouter Config

Batch Processing

Advanced Features

Custom System Prompt

Additional LLM Arguments

Multi-Agent Architecture Types

The boss agent can design swarms using various architectures:
  • AgentRearrange: Dynamic task reallocation
  • MixtureOfAgents: Parallel specialized processing
  • SequentialWorkflow: Linear task progression
  • ConcurrentWorkflow: Parallel execution
  • GroupChat: Collaborative discussion
  • HierarchicalSwarm: Layered decision-making
  • HeavySwarm: High-capacity specialized processing
  • MajorityVoting: Democratic decision-making
  • And more… Any SwarmType value is accepted

Source Code

View the source code on GitHub