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
Name of the swarm for identification and logging
Description of the swarm’s purpose and capabilities
List of Agent instances or callables to include in the swarm
List of language models to use across agents
Maximum number of execution loops for the swarm
Callback functions to execute during swarm operations
Automatically save swarm state to file
Enable detailed logging for debugging
Include metadata in return values
Filename for saving swarm metadata
Function that determines when the swarm should stop execution
Condition string that triggers swarm termination
Arguments passed to the stopping condition function
Function to select which agent should speak next in multi-agent conversations
Rules that govern swarm behavior and agent interactions
Shared memory system accessible by all agents
Enable AgentOps tracking for all agents in the swarm
Pydantic model defining the expected output structure
Core Methods
run
Execute the swarm’s main task loop.The task for the swarm to execute
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.The agent instance to add
add_agents
Add multiple agents to the swarm.List of agent instances to add
remove_agent
Remove an agent from the swarm.get_agent_by_name
Retrieve an agent by its name.Name of the agent to retrieve
The agent instance with matching name, or None if not found
get_agent_by_id
Retrieve an agent by its ID.ID of the agent to retrieve
The agent instance with matching ID, or None if not found
agent_exists
Check if an agent exists in the swarm.Name of the agent to check
True if agent exists, False otherwise
Task Management
assign_task
Assign a specific task to an agent.The agent to assign the task to
The task to assign
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.Message to broadcast
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 of tasks to execute
List of results for each task
run_batch
Alias for batched_run.concurrent_run
Run a task concurrently across all agents.Task to run on all agents
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.Number of agents to add
scale_down
Decrease the number of agents.Number of agents to remove
scale_to
Scale to a specific number of agents.Target number of agents
State Management
save_to_json
Save swarm state to JSON file.Path to save JSON file
load_from_json
Load swarm state from JSON file.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.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