> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Client

> Official Python client library for the Swarms API with comprehensive features and examples

## Features

* **Type Safety**: Full type definitions for all request params and response fields
* **Dual Clients**: Both synchronous and asynchronous clients powered by httpx
* **Comprehensive Coverage**: Access to all Swarms API endpoints
* **Modern Python**: Built for Python 3.8+ with async/await support
* **Environment Integration**: Seamless .env file support for API keys

## Installation

```bash theme={null}
pip install swarms-client
```

## Environment Setup

Create a `.env` file in your project root:

```bash theme={null}
SWARMS_API_KEY=your_api_key_here
```

## Quick Start

```python theme={null}
import os
from swarms_client import SwarmsClient
from dotenv import load_dotenv

load_dotenv()

client = SwarmsClient(
    api_key=os.getenv("SWARMS_API_KEY"),
    base_url="https://api.swarms.world",
)
```

### Your First Swarm

```python theme={null}
# Define your task
task_description = """
Analyze the following patient symptoms and provide ICD code recommendations:
- 45-year-old female with chest pain
- Shortness of breath for 2 days
- Sharp chest pain worsening with deep breathing
- Mild fever (100.2°F) and dry cough
"""

# Create and run a swarm
response = client.swarms.run(
    name="Medical Analysis Swarm",
    description="A swarm that analyzes patient symptoms and provides ICD codes",
    swarm_type="ConcurrentWorkflow",
    task=task_description,
    agents=[
        {
            "agent_name": "Symptom Analyzer",
            "description": "Analyzes patient symptoms and identifies key indicators",
            "system_prompt": "You are a medical expert. Analyze symptoms and identify key medical indicators.",
            "model_name": "groq/openai/gpt-oss-120b",
            "role": "worker",
            "max_loops": 1,
            "max_tokens": 8192,
            "temperature": 0.3,
        },
        {
            "agent_name": "ICD Code Specialist",
            "description": "Provides appropriate ICD codes based on symptom analysis",
            "system_prompt": "You are an ICD coding specialist. Provide accurate ICD codes with explanations.",
            "model_name": "groq/openai/gpt-oss-120b",
            "role": "worker",
            "max_loops": 1,
            "max_tokens": 8192,
            "temperature": 0.2,
        }
    ],
)

print(response)
```

## Client Configuration

### Environment Variable

Set `SWARMS_API_KEY` in your environment (or a `.env` file), then load it in your code:

```python theme={null}
import os
from dotenv import load_dotenv
load_dotenv()

client = SwarmsClient()  # Automatically uses SWARMS_API_KEY from environment
```

### Direct API Key

```python theme={null}
client = SwarmsClient(api_key="your_api_key_here")
```

### Custom Configuration

```python theme={null}
client = SwarmsClient(
    api_key=os.getenv("SWARMS_API_KEY"),
    base_url="https://api.swarms.world",  # Recommended: set explicitly
    timeout=30.0,  # Request timeout in seconds (SDK default: 60s)
    max_retries=2,  # Retries on transient errors (SDK default: 2)
)
```

<Note>
  If `base_url` is omitted, the installed `swarms-client` falls back to its own
  built-in default host rather than `https://api.swarms.world`. Always pass
  `base_url="https://api.swarms.world"` explicitly to avoid depending on
  whatever host ships baked into a given SDK version.
</Note>

## Core Operations

### Single Agent Completion

```python theme={null}
# Run a single agent (POST /v1/agent/completions)
agent_response = client.agent.run(
    agent_config={
        "agent_name": "research-agent",
        "system_prompt": "You are a concise research assistant.",
        "model_name": "gpt-4.1",
        "max_loops": 1,
        "max_tokens": 4096,
        "temperature": 0.3,
    },
    task="Summarize the key drivers of inflation in 2024.",
)

print(agent_response["outputs"])
print(agent_response["usage"])
```

### Swarm Management

```python theme={null}
# Create and run a swarm (POST /v1/swarm/completions)
swarm_response = client.swarms.run(
    name="Data Analysis Swarm",
    description="Analyzes complex datasets",
    swarm_type="SequentialWorkflow",
    task="Analyze the sales data for Q4",
    agents=[
        {"agent_name": "data-cleaner", "model_name": "gpt-4.1", "max_loops": 1},
        {"agent_name": "analyst", "model_name": "gpt-4.1", "max_loops": 1},
    ],
)

# Get request logs — GET /v1/swarm/logs (a deprecated alias for GET /v1/account/logs)
logs = client.swarms.get_logs()

# Check available swarm types — GET /v1/swarms/available
available = client.swarms.check_available()
```

<Note>
  `client.swarms.get_logs()` calls `GET /v1/swarm/logs`, a deprecated alias.
  The canonical endpoint, `GET /v1/account/logs`, is not yet exposed on this
  SDK resource; call it directly with `requests` — see
  [Endpoints Not Yet in the SDK](#endpoints-not-yet-in-the-sdk) below.
</Note>

### Model Information

```python theme={null}
# List available models
models = client.models.list_available()
```

### Health and Status

```python theme={null}
# Check API health
health_status = client.health.check()

# Get rate limits
rate_limits = client.client.rate.get_limits()

print(health_status)
print(rate_limits)
```

## Advanced Usage

### Asynchronous Operations

```python theme={null}
import asyncio
import os
from swarms_client import AsyncSwarmsClient

async def main():
    client = AsyncSwarmsClient(api_key=os.getenv("SWARMS_API_KEY"))

    # Run multiple operations concurrently
    results = await asyncio.gather(
        client.swarms.run(
            name="Task 1",
            swarm_type="ConcurrentWorkflow",
            task="Analyze customer feedback for Q1",
            agents=[
                {
                    "agent_name": "Feedback Analyst",
                    "system_prompt": "You analyze customer feedback and summarize key themes.",
                    "model_name": "gpt-4.1",
                }
            ],
        ),
        client.swarms.run(
            name="Task 2",
            swarm_type="ConcurrentWorkflow",
            task="Generate a monthly report summary",
            agents=[
                {
                    "agent_name": "Report Writer",
                    "system_prompt": "You write concise executive report summaries.",
                    "model_name": "gpt-4.1",
                }
            ],
        ),
        client.models.list_available(),
    )
    return results

# Run the async function
results = asyncio.run(main())
```

### Batch Operations

<Warning>
  `POST /v1/swarm/batch/completions` and `POST /v1/agent/batch/completions` are
  **premium-only** endpoints. Calling them on a free-tier API key returns an
  error. See [Premium Endpoints](/docs/documentation/resources/premium-endpoints).
</Warning>

Run several swarms concurrently in a single request with `client.swarms.batch.run`:

```python theme={null}
# POST /v1/swarm/batch/completions — executes all swarms concurrently server-side
batch_response = client.swarms.batch.run(
    body=[
        {
            "name": "Q1 Feedback Swarm",
            "swarm_type": "ConcurrentWorkflow",
            "task": "Analyze customer feedback for Q1",
            "agents": [
                {"agent_name": "analyst", "model_name": "gpt-4.1", "max_loops": 1}
            ],
        },
        {
            "name": "Monthly Report Swarm",
            "swarm_type": "ConcurrentWorkflow",
            "task": "Generate monthly report summary",
            "agents": [
                {"agent_name": "writer", "model_name": "gpt-4.1", "max_loops": 1}
            ],
        },
    ]
)

for result in batch_response:
    print(result["status"], result.get("swarm_name"))
```

The single-agent equivalent, `client.agent.batch.run`, takes a list of
`{"agent_config": ..., "task": ...}` objects and posts to
`/v1/agent/batch/completions` (batch limit: 50 agent completions per request):

```python theme={null}
# POST /v1/agent/batch/completions
agent_batch_response = client.agent.batch.run(
    body=[
        {
            "agent_config": {"agent_name": "analyst", "model_name": "gpt-4.1", "max_loops": 1},
            "task": "Analyze customer feedback for Q1",
        },
        {
            "agent_config": {"agent_name": "writer", "model_name": "gpt-4.1", "max_loops": 1},
            "task": "Generate monthly report summary",
        },
    ]
)
```

If you are on the free tier, run tasks sequentially against the
non-premium `client.swarms.run` or `client.agent.run` instead:

```python theme={null}
tasks = [
    "Analyze customer feedback for Q1",
    "Generate monthly report summary",
    "Review system performance metrics",
]

responses = [
    client.agent.run(
        agent_config={"agent_name": "worker", "model_name": "gpt-4.1", "max_loops": 1},
        task=task,
    )
    for task in tasks
]
```

## Helper Methods

The client provides convenient helper methods for common operations:

```python theme={null}
# Quick health check
if client.health.check()['status'] == 'ok':
    print("API is healthy!")

# Get available models with formatting
models = client.models.list_available()
print(f"Available models: {models['count']}")

# Check rate limits
limits = client.client.rate.get_limits()
minute = limits['rate_limits']['minute']
print(f"Current usage (last minute): {minute['count']}/{minute['limit']}")
print(f"Tier: {limits['tier']}")
```

## Examples

### Content Generation Swarm

```python theme={null}
content_swarm = client.swarms.run(
    name="Content Generation Swarm",
    description="Creates engaging content for social media",
    swarm_type="SequentialWorkflow",
    task="Create a blog post about AI trends in 2024",
    agents=[
        {
            "agent_name": "Research Agent",
            "description": "Researches current AI trends and statistics",
            "system_prompt": "You are a research specialist. Gather current information about AI trends.",
            "model_name": "groq/openai/gpt-oss-120b",
            "role": "researcher",
            "max_loops": 1,
            "max_tokens": 4096,
            "temperature": 0.3,
        },
        {
            "agent_name": "Writer Agent",
            "description": "Writes engaging blog content based on research",
            "system_prompt": "You are a professional writer. Create engaging blog content.",
            "model_name": "groq/openai/gpt-oss-120b",
            "role": "writer",
            "max_loops": 1,
            "max_tokens": 8192,
            "temperature": 0.7,
        }
    ],
)
```

### Data Analysis Pipeline

```python theme={null}
analysis_pipeline = client.swarms.run(
    name="Data Analysis Pipeline",
    description="Comprehensive data analysis workflow",
    swarm_type="SequentialWorkflow",
    task="Analyze quarterly sales data and provide insights",
    agents=[
        {
            "agent_name": "Data Validator",
            "description": "Validates and cleans input data",
            "system_prompt": "You are a data validation expert. Check data quality and format.",
            "model_name": "groq/openai/gpt-oss-120b",
            "role": "validator",
            "max_loops": 1,
            "max_tokens": 4096,
            "temperature": 0.1,
        },
        {
            "agent_name": "Statistical Analyst",
            "description": "Performs statistical analysis on the data",
            "system_prompt": "You are a statistical analyst. Perform comprehensive data analysis.",
            "model_name": "groq/openai/gpt-oss-120b",
            "role": "analyst",
            "max_loops": 1,
            "max_tokens": 8192,
            "temperature": 0.2,
        },
        {
            "agent_name": "Insight Generator",
            "description": "Generates actionable insights from analysis",
            "system_prompt": "You are a business analyst. Generate actionable insights.",
            "model_name": "groq/openai/gpt-oss-120b",
            "role": "insights",
            "max_loops": 1,
            "max_tokens": 4096,
            "temperature": 0.5,
        }
    ],
)
```

## Endpoints Not Yet in the SDK

The installed `swarms-client` (0.8.0) wraps a subset of the Swarms API:
`client.agent.run`, `client.agent.batch.run`, `client.swarms.run`,
`client.swarms.batch.run`, `client.swarms.get_logs`,
`client.swarms.check_available`, `client.models.list_available`,
`client.health.check`, and `client.client.rate.get_limits`.

Newer endpoints — reasoning agents, graph workflows, batched grid workflows,
the auto agent builder, and the account/usage endpoints — are not yet
wrapped by a dedicated resource. Call them directly with `requests` using
the same `x-api-key` header:

```python theme={null}
import os
import requests

API_KEY = os.getenv("SWARMS_API_KEY")
BASE_URL = "https://api.swarms.world"
HEADERS = {"x-api-key": API_KEY, "Content-Type": "application/json"}

# Reasoning agent completion — POST /v1/reasoning-agent/completions (premium)
reasoning = requests.post(
    f"{BASE_URL}/v1/reasoning-agent/completions",
    headers=HEADERS,
    json={
        "agent_name": "reasoning-agent",
        "model_name": "claude-sonnet-5",
        "swarm_type": "reasoning-duo",
        "task": "Should we launch the product in Q2 or Q3?",
    },
)
print(reasoning.json())

# Reasoning agent types — GET /v1/reasoning-agent/types
reasoning_types = requests.get(
    f"{BASE_URL}/v1/reasoning-agent/types", headers=HEADERS
).json()

# Graph workflow — POST /v1/graph-workflow/completions (premium)
graph = requests.post(
    f"{BASE_URL}/v1/graph-workflow/completions",
    headers=HEADERS,
    json={
        "name": "research-pipeline",
        "agents": [
            {"agent_name": "researcher", "model_name": "gpt-4.1", "max_loops": 1},
            {"agent_name": "writer", "model_name": "gpt-4.1", "max_loops": 1},
        ],
        "edges": [{"source": "researcher", "target": "writer"}],
        "task": "Research and write a one-page brief on solid-state batteries.",
    },
)

# Batched grid workflow — POST /v1/batched-grid-workflow/completions (premium)
grid = requests.post(
    f"{BASE_URL}/v1/batched-grid-workflow/completions",
    headers=HEADERS,
    json={
        "agent_completions": [
            {"agent_name": "worker", "model_name": "gpt-4.1", "max_loops": 1}
        ],
        "tasks": ["Summarize article A", "Summarize article B"],
    },
)

# Auto agent builder — POST /v1/auto-agent-builder/completions (generates AgentSpecs, does not execute them)
builder = requests.post(
    f"{BASE_URL}/v1/auto-agent-builder/completions",
    headers=HEADERS,
    json={"task": "Build a team that triages customer support tickets.", "max_agents": 3},
).json()
generated_agents = builder["agents"]  # ready-to-post AgentSpec objects

# Account credit balance — GET /v1/account/credits
credits = requests.get(f"{BASE_URL}/v1/account/credits", headers=HEADERS).json()

# API request logs — GET /v1/account/logs (canonical; /v1/swarm/logs is a deprecated alias)
account_logs = requests.get(f"{BASE_URL}/v1/account/logs", headers=HEADERS).json()

# Usage metrics summary — GET /v1/account/metrics/summary
metrics = requests.get(f"{BASE_URL}/v1/account/metrics/summary", headers=HEADERS).json()

# Which endpoints require a premium subscription — GET /v1/account/premium-endpoints
premium_info = requests.get(f"{BASE_URL}/v1/account/premium-endpoints", headers=HEADERS).json()

# Pricing details — GET /v1/usage/costs
pricing = requests.get(f"{BASE_URL}/v1/usage/costs", headers=HEADERS).json()

# Saved agent configurations — GET /v1/agents/list
saved_agents = requests.get(f"{BASE_URL}/v1/agents/list", headers=HEADERS).json()

# Available API tools (auto_search, web_scraper) — GET /v1/tools/available
tools = requests.get(f"{BASE_URL}/v1/tools/available", headers=HEADERS).json()

# OpenAI-compatible chat completions — POST /v1/chat/completions
chat = requests.post(
    f"{BASE_URL}/v1/chat/completions",
    headers=HEADERS,
    json={"model": "gpt-4.1", "messages": [{"role": "user", "content": "Hello"}]},
).json()

# OpenAI-compatible model list — GET /v1/models
openai_models = requests.get(f"{BASE_URL}/v1/models", headers=HEADERS).json()
```

<Tip>
  The OpenAI-compatible endpoints (`/v1/chat/completions`, `/v1/models`) also
  work as a drop-in with the official `openai` Python SDK: pass
  `base_url="https://api.swarms.world/v1"` and `api_key=os.getenv("SWARMS_API_KEY")`
  to `OpenAI(...)`.
</Tip>

## Troubleshooting

### Common Issues

1. **API Key Errors**: Ensure your API key is valid and properly set in environment variables
2. **Rate Limiting**: Check rate limits with `client.client.rate.get_limits()`
3. **Network Issues**: Verify your internet connection and firewall settings
4. **Model Availability**: Use `client.models.list_available()` to check available models

### Getting Help

* **GitHub**: [swarms-client repository](https://github.com/The-Swarm-Corporation/swarms-client)
* **Support**: Check our [technical support page](/docs/documentation/resources/technical-support)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.