Skip to main content

Overview

The BaseSwarm class is an abstract base class (ABC) that provides the foundation for all multi-agent systems in the Swarms framework. It defines the core interface and common functionality for orchestrating multiple agents to work together on complex tasks.

Import

Key Features

  • Agent Management: Add, remove, and query agents in the swarm
  • Task Distribution: Assign tasks to specific agents or broadcast to all
  • Lifecycle Management: Pause, resume, stop, and restart agents
  • Scaling: Dynamic agent scaling (scale up/down/to specific size)
  • State Management: Save and load swarm state
  • Batch Operations: Run tasks across multiple agents concurrently
  • Async Support: Full async/await support for concurrent execution
  • Conversation Management: Built-in conversation tracking

Initialization

str
Name of the swarm for identification and logging
str
Description of the swarm’s purpose and capabilities
List[Union[Agent, Callable]]
List of Agent instances or callables to include in the swarm
List[Any]
List of language models to use across agents
int
default:"200"
Maximum number of execution loops for the swarm
Sequence[callable]
Callback functions to execute during swarm operations
bool
default:"false"
Automatically save swarm state to file
bool
default:"false"
Enable detailed logging for debugging
bool
default:"false"
Include metadata in return values
str
default:"multiagent_structure_metadata.json"
Filename for saving swarm metadata
Callable
Function that determines when the swarm should stop execution
str
default:"stop"
Condition string that triggers swarm termination
Dict
Arguments passed to the stopping condition function
Callable
Function to select which agent should speak next in multi-agent conversations
str
Rules that govern swarm behavior and agent interactions
Any
default:"false"
Shared memory system accessible by all agents
bool
default:"false"
Enable AgentOps tracking for all agents in the swarm
BaseModel
Pydantic model defining the expected output structure

Core Methods

run

Execute the swarm’s main task loop. In BaseSwarm this is an unimplemented placeholder (def run(self): ..., no parameters) — subclasses are expected to override it. __call__ and the various *_run/*batch* helpers all invoke self.run(task, *args, **kwargs), so overrides should accept at least a task argument.
str
The task for the swarm to execute
Any
Result of swarm execution (implementation-specific)

call

Alternative syntax for running the swarm (calls run internally).

Agent Management

add_agent

Add a single agent to the swarm.
AgentType
The agent instance to add

add_agents

Add multiple agents to the swarm.
List[AgentType]
List of agent instances to add

add_agent_by_id

Look up an agent by ID via get_agent_by_id and add it to the swarm.

remove_agent

Remove an agent from the swarm.

get_agent_by_name

Retrieve an agent by its name.
str
Name of the agent to retrieve
AgentType
The agent instance with matching name, or None if not found

get_agent_by_id

Retrieve an agent by its ID.
str
ID of the agent to retrieve
AgentType
The agent instance with matching ID, or None if not found

self_find_agent_by_name / self_find_agent_by_id

Find an agent within self.agents by name or ID. Thin wrappers around the module-level find_agent_by_name / find_agent_by_id helpers.

Task Management

assign_task

Assign a specific task to an agent.
AgentType
The agent to assign the task to
Any
The task to assign
Dict
Task execution result

task_assignment_by_name

Assign a task to an agent by name.

task_assignment_by_id

Assign a task to an agent by ID (looked up via select_agent, not get_agent_by_id).

get_all_tasks / get_finished_tasks / get_pending_tasks

Placeholder stubs for task-tracking (unimplemented in BaseSwarm).

broadcast

Broadcast a message to all agents in the swarm.
str
Message to broadcast
AgentType
Optional sender agent

direct_message

Send a direct message from one agent to another.

Batch Operations

batched_run

Run multiple tasks in batch mode.
List[Any]
List of tasks to execute
List[Any]
List of results for each task

run_batch

Alias for batched_run.

concurrent_run

Run a task concurrently across all agents.
str
Task to run on all agents
List[str]
List of responses from each agent
concurrent_run appends to self.task_history, which BaseSwarm.__init__ does not initialize. Calling it on a fresh instance without something else having set self.task_history first will raise AttributeError.

run_all

Run a task on all agents sequentially.

run_on_all_agents

Run a task on all agents using ThreadPoolExecutor.

Async Operations

arun

Run the swarm asynchronously.

abatch_run

Run multiple tasks asynchronously in batch.

run_async

Run the swarm asynchronously (synchronous wrapper).

run_batch_async

Run batch tasks asynchronously (synchronous wrapper).

Lifecycle Management

pause_agent

Pause an agent’s execution.

resume_agent

Resume a paused agent.

stop_agent

Stop an agent’s execution.

restart_agent

Restart an agent.

reset_all_agents

Reset the state of all agents.

Scaling

scale_up, scale_down, and scale_to are unimplemented placeholders in BaseSwarm (docstring only, no body) — subclasses must override them to actually add/remove agents.

scale_up

Increase the number of agents.
int
Number of agents to add

scale_down

Decrease the number of agents.
int
Number of agents to remove

scale_to

Scale to a specific number of agents.
int
Target number of agents

get_all_agents / get_swarm_size / get_swarm_status / save_swarm_state

Placeholder stubs (unimplemented in BaseSwarm) intended for subclasses to override.

add_llm / remove_llm

Add or remove a callable/agent from self.agents (aliases predating the add_agent/remove_agent naming).

loop / aloop

Call run(task, *args, **kwargs) repeatedly, max_loops times. aloop runs loop in an executor.

State Management

save_to_json

Save swarm state to JSON file.
str
Path to save JSON file

load_from_json

Load swarm state from JSON file.
str
Path to JSON file to load

save_to_yaml

Save swarm state to YAML file.

load_from_yaml

Load swarm state from YAML file.

metadata

Get swarm metadata.
dict
Dictionary containing swarm metadata (agents, callbacks, autosave, logging, conversation)

Examples

Basic Swarm Implementation

Dynamic Agent Management

Batch Task Processing

Async Swarm Execution

Swarm with State Persistence

Properties

BaseSwarm provides several built-in properties:
  • agents_dict: Dictionary mapping agent names to agent instances
  • conversation: Conversation object for tracking agent interactions

Sequence/Container Protocol

BaseSwarm implements the standard container dunder methods over self.agents, so a swarm instance can be used like a list of agents:

Registry & Miscellaneous Stubs

The following are unimplemented placeholder methods (docstring only, no body) intended for subclasses that maintain a swarm registry:

Best Practices

  1. Always validate agents: Ensure agents list is not empty and all agents are valid
  2. Implement abstract methods: Override run(), communicate(), and other abstract methods
  3. Use async for I/O-bound tasks: Leverage async methods for better performance
  4. Enable autosave for long-running swarms: Prevent state loss
  5. Set appropriate max_loops: Prevent infinite loops
  6. Use callbacks for monitoring: Track swarm execution progress
  7. Implement proper error handling: Handle agent failures gracefully
  8. Scale dynamically based on load: Use scaling methods to optimize resources