Skip to main content

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-sdk

Quick Start

import asyncio
from swarms_sdk 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_sdk 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

  1. API Key Management

    • Use environment variables for API keys
    • Never commit API keys to version control
    • Rotate API keys regularly
  2. Error Handling

    • Always wrap API calls in try-except blocks
    • Handle specific exceptions appropriately
    • Implement retry logic for transient failures
  3. Resource Management

    • Use async context manager for proper session cleanup
    • Close client sessions when done
    • Monitor memory usage with large swarms
  4. 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

swarms_client-0.1.0.tar.gz (6.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

swarms_client-0.1.0-py3-none-any.whl (8.0 kB view details)

Uploaded Python 3

File details

Details for the file swarms_client-0.1.0.tar.gz.

File metadata

  • Download URL: swarms_client-0.1.0.tar.gz
  • Upload date:
  • Size: 6.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

Hashes for swarms_client-0.1.0.tar.gz
Algorithm Hash digest
SHA256 774ff6fc0e2a22e06272cfa8b26d2b6ba9d635d874299c21e9165baffa21ab41
MD5 6161f6302eb73282d853304b314154d1
BLAKE2b-256 cec1c8d121e886ebb33bd69646901eb222dfdacb1ad35a9a884ef420c19284ec

See more details on using hashes here.

File details

Details for the file swarms_client-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: swarms_client-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 8.0 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

Hashes for swarms_client-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fe125f15ce61d4e77afe2d2fbfd069aaf271ff80ddcfc67145e29105a6e23b14
MD5 f91e0873d2ef4c27891b4940ce0a32c2
BLAKE2b-256 dace372565890d6ce06decb00cac00d17ba2b71a1455e585c370656453c13870

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page