Overview
TheBaseSwarm 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.str
The task for the swarm to execute
Any
Result of swarm execution (implementation-specific)
call
Alternative syntax for running the swarm (callsrun 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
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
agent_exists
Check if an agent exists in the swarm.str
Name of the agent to check
bool
True if agent exists, False otherwise
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.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
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
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
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 instancesconversation: Conversation object for tracking agent interactions
Best Practices
- Always validate agents: Ensure agents list is not empty and all agents are valid
- Implement abstract methods: Override
run(),communicate(), and other abstract methods - Use async for I/O-bound tasks: Leverage async methods for better performance
- Enable autosave for long-running swarms: Prevent state loss
- Set appropriate max_loops: Prevent infinite loops
- Use callbacks for monitoring: Track swarm execution progress
- Implement proper error handling: Handle agent failures gracefully
- Scale dynamically based on load: Use scaling methods to optimize resources
Related
- Agent - Core agent implementation
- BaseStructure - Base class for structures
- Swarm Architectures - Different swarm patterns