Skip to main content

Overview

The BaseStructure 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

str
Name of the structure for identification and file naming
str
Description of the structure’s purpose
bool
default:"true"
Enable automatic metadata saving
str
default:"./artifacts"
Directory path for saving artifacts
str
default:"./metadata"
Directory path for saving metadata
str
default:"./errors"
Directory path for saving error logs

Core Methods

run

Execute the structure’s main operation (abstract method to be implemented by subclasses).
Any
Implementation-specific return value

File Operations

save_to_file

Save data to a JSON file.
Any
Data to save (must be JSON serializable)
str
Path to save the file

load_from_file

Load data from a JSON file.
str
Path to the file to load
Any
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.
Dict[str, Any]
Metadata dictionary to save

load_metadata

Load metadata from a JSON file.
Dict[str, Any]
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.
Any
Artifact data to save
str
Name for the artifact file (without extension)

load_artifact

Load an artifact from a JSON file.
str
Name of the artifact to load
Any
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.
str
Error message to log

log_error_async

Asynchronously log an error.

log_event

Log an event with timestamp and type.
str
Event description
str
default:"INFO"
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.
concurrent.futures.Future
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[Any]
List of data items to process
int
default:"10"
Number of concurrent workers
List[Any]
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.
Any
Data to compress (must be JSON serializable)
bytes
Compressed data as bytes

decompres_data

Decompress gzip data.
bytes
Compressed data to decompress
Any
Decompressed data

Resource Monitoring

monitor_resources

Monitor CPU and memory usage.
Logs current CPU and memory usage to the event log.

run_with_resources

Run the structure with resource monitoring.

Configuration

load_config

Load configuration from a file.
str
Path to configuration file
Dict[str, Any]
Configuration dictionary

backup_data

Backup data with timestamp.
Any
Data to backup
str
Path to backup directory

Serialization

to_dict

Convert structure to dictionary.
Dict[str, Any]
Dictionary representation of the structure

to_json

Convert structure to JSON string.
int
default:"4"
Number of spaces for indentation
str
JSON string representation

to_yaml

Convert structure to YAML string.
int
default:"4"
Number of spaces for indentation
str
YAML string representation

to_toml

Convert structure to TOML string.
str
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 structure
  • description: Description of the structure
  • save_metadata_on: Whether metadata saving is enabled
  • save_artifact_path: Path for artifacts
  • save_metadata_path: Path for metadata
  • save_error_path: Path for error logs

Best Practices

  1. Always call super().init(): When extending BaseStructure, call parent constructor
  2. Implement the run method: Override the abstract run() method with your logic
  3. Use logging methods: Leverage log_event and log_error for tracking
  4. Save artifacts: Use save_artifact for important outputs
  5. Handle errors gracefully: Wrap operations in try/except and use log_error
  6. Use async for I/O: Leverage async methods for file operations
  7. Monitor resources: Use run_with_resources for resource-intensive tasks
  8. Batch when possible: Use run_batched for processing multiple items
  9. Compress large data: Use compress_data for large datasets
  10. Enable metadata: Set save_metadata_on=True for production systems