Overview
TheBaseStructure class provides the foundational infrastructure for all swarm structures and agent systems in the Swarms framework. It offers essential utilities for state management, file I/O, metadata tracking, error logging, and resource monitoring.
Import
Key Features
- File Operations: Save and load data in JSON, YAML, and TOML formats
- State Management: Automatic metadata and artifact tracking
- Error Logging: Centralized error logging to files
- Event Tracking: Log events with timestamps and severity levels
- Async Support: Full async/await support for I/O operations
- Thread Support: Run operations in separate threads
- Batch Processing: Process multiple tasks concurrently
- Data Compression: Built-in gzip compression/decompression
- Resource Monitoring: Track CPU and memory usage
- Serialization: Convert structures to dict/JSON/YAML/TOML
Initialization
Name of the structure for identification and file naming
Description of the structure’s purpose
Enable automatic metadata saving
Directory path for saving artifacts
Directory path for saving metadata
Directory path for saving error logs
Core Methods
run
Execute the structure’s main operation (abstract method to be implemented by subclasses).Implementation-specific return value
File Operations
save_to_file
Save data to a JSON file.Data to save (must be JSON serializable)
Path to save the file
load_from_file
Load data from a JSON file.Path to the file to load
Loaded data from the JSON file
asave_to_file
Asynchronously save data to a file.aload_from_file
Asynchronously load data from a file.Metadata Management
save_metadata
Save metadata to a JSON file.Metadata dictionary to save
load_metadata
Load metadata from a JSON file.Loaded metadata dictionary
save_metadata_async
Asynchronously save metadata.load_metadata_async
Asynchronously load metadata.Artifact Management
save_artifact
Save an artifact to a JSON file.Artifact data to save
Name for the artifact file (without extension)
load_artifact
Load an artifact from a JSON file.Name of the artifact to load
Loaded artifact data
save_artifact_async
Asynchronously save an artifact.load_artifact_async
Asynchronously load an artifact.Error and Event Logging
log_error
Log an error message to file.Error message to log
log_error_async
Asynchronously log an error.log_event
Log an event with timestamp and type.Event description
Event type (INFO, WARNING, ERROR, etc.)
log_event_async
Asynchronously log an event.Async Operations
run_async
Run the structure asynchronously.run_concurrent
Run the structure concurrently using asyncio.Thread Operations
run_in_thread
Run the structure in a separate thread.Future object representing the thread execution
save_metadata_in_thread
Save metadata in a separate thread.Batch Processing
run_batched
Run multiple tasks in batches using ThreadPoolExecutor.List of data items to process
Number of concurrent workers
List of results for each batch item
run_with_resources_batched
Run batched data with resource monitoring.Data Compression
compress_data
Compress data using gzip.Data to compress (must be JSON serializable)
Compressed data as bytes
decompres_data
Decompress gzip data.Compressed data to decompress
Decompressed data
Resource Monitoring
monitor_resources
Monitor CPU and memory usage.run_with_resources
Run the structure with resource monitoring.Configuration
load_config
Load configuration from a file.Path to configuration file
Configuration dictionary
backup_data
Backup data with timestamp.Data to backup
Path to backup directory
Serialization
to_dict
Convert structure to dictionary.Dictionary representation of the structure
to_json
Convert structure to JSON string.Number of spaces for indentation
JSON string representation
to_yaml
Convert structure to YAML string.Number of spaces for indentation
YAML string representation
to_toml
Convert structure to TOML string.TOML string representation
Examples
Basic Structure Implementation
Async Structure
Batch Processing Structure
Structure with Resource Monitoring
Structure with Error Handling
Data Compression Example
Serialization Example
Properties
BaseStructure provides the following properties:workspace_dir: Path to the workspace directory (from environment variable)name: Name of the structuredescription: Description of the structuresave_metadata_on: Whether metadata saving is enabledsave_artifact_path: Path for artifactssave_metadata_path: Path for metadatasave_error_path: Path for error logs
Best Practices
- Always call super().init(): When extending BaseStructure, call parent constructor
- Implement the run method: Override the abstract run() method with your logic
- Use logging methods: Leverage log_event and log_error for tracking
- Save artifacts: Use save_artifact for important outputs
- Handle errors gracefully: Wrap operations in try/except and use log_error
- Use async for I/O: Leverage async methods for file operations
- Monitor resources: Use run_with_resources for resource-intensive tasks
- Batch when possible: Use run_batched for processing multiple items
- Compress large data: Use compress_data for large datasets
- Enable metadata: Set save_metadata_on=True for production systems
Related
- Agent - Core agent implementation built on BaseStructure
- BaseSwarm - Multi-agent swarm base class
- State Management - Managing agent and swarm state