A production-grade Python client for the Swarms API
Project description
Swarms SDK
A production-grade Python client for the Swarms API, providing a simple and intuitive interface for creating and managing AI swarms.
Features
- 🚀 Async-first design with comprehensive error handling
- 📝 Extensive logging with loguru
- 🔄 Automatic retries with exponential backoff
- 🔒 Secure API key management
- 📊 Detailed telemetry and monitoring
- 🎯 Type hints and validation
- 📚 Comprehensive documentation
Installation
pip install swarms-client
Quick Start
import asyncio
from swarms_client import SwarmsClient
async def main():
# Initialize the client
client = SwarmsClient(api_key="your-api-key")
# Create a swarm
swarm = await client.create_swarm(
name="my-swarm",
task="Analyze this data",
agents=[
{
"agent_name": "analyzer",
"model_name": "gpt-4",
"role": "worker"
}
]
)
# Run the swarm
result = await client.run_swarm(swarm["id"])
print(result)
# Run the async function
asyncio.run(main())
API Reference
SwarmsClient
The main client class for interacting with the Swarms API.
Initialization
client = SwarmsClient(
api_key="your-api-key", # Optional: Can also use SWARMS_API_KEY env var
base_url="https://api.swarms.world", # Optional: Default API URL
timeout=60, # Optional: Request timeout in seconds
max_retries=3 # Optional: Maximum retry attempts
)
Methods
create_swarm
Create a new swarm with specified configuration.
swarm = await client.create_swarm(
name="my-swarm",
task="Analyze this data",
agents=[
{
"agent_name": "analyzer",
"model_name": "gpt-4",
"role": "worker"
}
],
description="Optional description",
max_loops=1,
swarm_type="SequentialWorkflow",
service_tier="standard"
)
run_swarm
Run a swarm with the specified ID.
result = await client.run_swarm(swarm_id="swarm-123")
get_swarm_logs
Get execution logs for a specific swarm.
logs = await client.get_swarm_logs(swarm_id="swarm-123")
get_available_models
Get list of available models.
models = await client.get_available_models()
get_swarm_types
Get list of available swarm types.
swarm_types = await client.get_swarm_types()
Error Handling
The SDK provides custom exceptions for different error scenarios:
from swarms_client import (
SwarmsError,
AuthenticationError,
RateLimitError,
ValidationError,
APIError
)
try:
result = await client.run_swarm(swarm_id)
except AuthenticationError as e:
print("Authentication failed:", e)
except RateLimitError as e:
print("Rate limit exceeded:", e)
except APIError as e:
print(f"API error (status {e.status_code}):", e)
except SwarmsError as e:
print("Other error:", e)
Logging
The SDK uses loguru for comprehensive logging. Logs are written to both console and file:
import loguru
# Configure custom logging
loguru.logger.add(
"custom.log",
rotation="100 MB",
retention="7 days",
level="DEBUG"
)
Best Practices
-
API Key Management
- Use environment variables for API keys
- Never commit API keys to version control
- Rotate API keys regularly
-
Error Handling
- Always wrap API calls in try-except blocks
- Handle specific exceptions appropriately
- Implement retry logic for transient failures
-
Resource Management
- Use async context manager for proper session cleanup
- Close client sessions when done
- Monitor memory usage with large swarms
-
Performance
- Use appropriate service tiers
- Implement caching where appropriate
- Monitor API rate limits
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file swarms_client-0.1.3.tar.gz.
File metadata
- Download URL: swarms_client-0.1.3.tar.gz
- Upload date:
- Size: 13.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.3 CPython/3.12.8 Darwin/24.3.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2fcf202d5ef239d7f450ac516fb59dea2d82a7af0f9c678a800ab80c2ef6d4ab
|
|
| MD5 |
af82808a99d125a386d2dabc1f69f46d
|
|
| BLAKE2b-256 |
38e1bdb1892d5e078407cb4c38efa26457a7b31c6062e741287b406b4c201ba6
|
File details
Details for the file swarms_client-0.1.3-py3-none-any.whl.
File metadata
- Download URL: swarms_client-0.1.3-py3-none-any.whl
- Upload date:
- Size: 14.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.3 CPython/3.12.8 Darwin/24.3.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0074801ce4fac0161910214bb4a387b34c773ececd51a8bedc958ee7de306971
|
|
| MD5 |
dff5628130af4af51662a26589388691
|
|
| BLAKE2b-256 |
772eef6ed625de889a932969e496c302883b92b8d631c0caa80cfcaef24598a8
|