Skill: newsoulontheblock/swarms-ai (version 1.0.0)

--- name: swarms-ai description: Build and orchestrate multi-agent AI systems using the Swarms API. Use when creating single agents, multi-agent swarms (sequential, concurrent, hierarchical, mixture-of-agents, majority voting, graph workflows), launching agent tokens on Solana, integrating ATP payment protocol, publishing to Swarms Marketplace, using sub-agent delegation, streaming responses, or building any multi-agent orchestration pipeline. Covers Python, TypeScript, and cURL. --- # Swarms AI — Multi-Agent Orchestration Build production-grade multi-agent systems using the Swarms API platform. Supports single agents, reasoning agents, and swarms of 3–10,000+ agents with 20+ architecture patterns. ## Quick Reference - **Base URL:** `https://api.swarms.world` - **Auth:** `x-api-key` header with API key from [swarms.world/platform/api-keys](https://swarms.world/platform/api-keys) - **Docs index:** `https://docs.swarms.ai/llms.txt` - **Python SDK:** `pip install swarms-client` - **Marketplace:** [swarms.world](https://swarms.world) ## Architecture Tiers | Tier | Name | Agents | Endpoint | |------|------|--------|----------| | 1 | Individual Agent | 1 | `/v1/agent/completions` | | 2 | Reasoning Agent | 1-2 internal | `/v1/reasoning-agent/completions` | | 3 | Multi-Agent Swarm | 3–10,000+ | `/v1/swarm/completions` | ## Workflow ### 1. Single Agent ```python import requests payload = { "agent_config": { "agent_name": "MyAgent", "description": "Purpose of the agent", "system_prompt": "You are...", "model_name": "gpt-4o", # or claude-sonnet-4-20250514, etc. "role": "worker", "max_loops": 1, "max_tokens": 8192, "temperature": 0.5, "auto_generate_prompt": False, "tools_list_dictionary": None }, "task": "Your task here" } response = requests.post( "https://api.swarms.world/v1/agent/completions", headers={"x-api-key": API_KEY, "Content-Type": "application/json"}, json=payload ) ``` ### 2. Multi-Agent Swarm ```python payload = { "name": "My Swarm", "description": "What this swarm does", "agents": [ { "agent_name": "Agent1", "description": "Role 1", "system_prompt": "You are...", "model_name": "gpt-4o", "role": "worker", "max_loops": 1, "max_tokens": 8192, "temperature": 0.5 }, { "agent_name": "Agent2", "description": "Role 2", "system_prompt": "You are...", "model_name": "claude-sonnet-4-20250514", "role": "worker", "max_loops": 1, "max_tokens": 8192, "temperature": 0.5 } ], "max_loops": 1, "swarm_type": "SequentialWorkflow", # See architecture table "task": "Your task here" } response = requests.post( "https://api.swarms.world/v1/swarm/completions", headers={"x-api-key": API_KEY, "Content-Type": "application/json"}, json=payload ) ``` ### 3. Token Launch (Solana) ```python payload = { "name": "My Agent Token", "description": "Agent description", "ticker": "MAG", "private_key": "[1,2,3,...]" # Solana wallet private key } response = requests.post( "https://swarms.world/api/token/launch", headers={"Authorization": "Bearer API_KEY", "Content-Type": "application/json"}, json=payload ) # Returns: token_address, pool_address, listing_url # Cost: ~0.04 SOL ``` ## Available Swarm Architectures Use the `swarm_type` parameter: | Type | Description | Best For | |------|-------------|----------| | `SequentialWorkflow` | Linear pipeline, each agent builds on previous | Step-by-step processing | | `ConcurrentWorkflow` | Parallel execution | Independent tasks, speed | | `AgentRearrange` | Dynamic agent reordering | Adaptive workflows | | `MixtureOfAgents` | Specialist agent selection | Multi-domain tasks | | `MultiAgentRouter` | Intelligent task routing | Large-scale distribution | | `HierarchicalSwarm` | Nested hierarchies with delegation | Complex org structures | | `MajorityVoting` | Consensus across agents | Decision making | | `BatchedGridWorkflow` | Grid pattern execution | Multi-task × multi-agent | | `GraphWorkflow` | Directed graph of agent nodes | Complex dependencies | | `GroupChat` | Agent discussion | Collaborative brainstorming | | `InteractiveGroupChat` | Real-time agent interaction | Dynamic collaboration | | `AutoSwarmBuilder` | Auto-generate optimal swarm | When unsure of architecture | | `HeavySwarm` | High-capacity processing | Large workloads | | `DebateWithJudge` | Structured debate | Adversarial evaluation | | `RoundRobin` | Round-robin distribution | Even load distribution | | `MALT` | Multi-agent learning | Training systems | | `CouncilAsAJudge` | Expert panel evaluation | Quality assessment | | `LLMCouncil` | LM council for decisions | Group decision making | | `AdvancedResearch` | Research workflows | Deep research | | `auto` | Auto-select best type | Default/unknown | ## Agent Config Parameters | Param | Type | Default | Description | |-------|------|---------|-------------| | `agent_name` | string | — | Unique agent identifier | | `description` | string | — | Agent purpose | | `system_prompt` | string | — | Behavior instructions | | `model_name` | string | `gpt-4.1` | AI model (gpt-4o, claude-sonnet-4-20250514, etc.) | | `role` | string | `worker` | Agent role in swarm | | `max_loops` | int/string | `1` | Iterations (`"auto"` for autonomous) | | `max_tokens` | int | `8192` | Max response length | | `temperature` | float | `0.5` | Creativity (0.0–2.0) | | `auto_generate_prompt` | bool | `false` | Auto-enhance system prompt | | `tools_list_dictionary` | list | — | OpenAPI-style tool definitions | | `streaming_on` | bool | `false` | Enable SSE streaming | | `mcp_url` | string | — | MCP server URL | | `selected_tools` | list | all safe | Restrict available tools | ## Rules - Always use environment variables for API keys — never hardcode. - Set appropriate `max_loops` — use `"auto"` only when sub-agent delegation is needed. - Match `swarm_type` to use case (see architecture table). - For streaming, set `streaming_on: true` and parse SSE events (metadata → chunks → usage → done). - Token launches cost ~0.04 SOL from the provided wallet. - Batch endpoint (`/v1/swarm/batch/completions`) requires Pro/Ultra/Premium tier. - Reasoning agents (`/v1/reasoning-agent/completions`) require Pro+ tier. ## Resource Map | Topic | Reference | |-------|-----------| | Full API architecture & tiers | `references/architecture.md` | | Sub-agent delegation patterns | `references/sub-agents.md` | | ATP payment protocol (Solana) | `references/atp-protocol.md` | | Marketplace publishing | `references/marketplace.md` | | Streaming implementation | `references/streaming.md` | | Tools integration | `references/tools.md` | | All docs pages | https://docs.swarms.ai/llms.txt | Read references only when the task requires that specific depth.

path: references/architecture.md
content: # Swarms API Architecture

## Three-Tier System

### Tier 1: Individual Agents
- Endpoint: `POST /v1/agent/completions`
- Single AI model per agent, focused tasks
- Use cases: content generation, data analysis, Q&A, tool execution
- Config: `agent_config` (AgentSpec) + `task` string
- Optional: `history` (conversation context), `img`/`imgs` (base64 images), `tools_enabled`

### Tier 2: Reasoning Agents (Pro+ only)
- Endpoint: `POST /v1/reasoning-agent/completions`
- 1-2 internal sub-agents for complex reasoning
- Types:
  - `reasoning-duo` — dual perspectives, synthesis
  - `self-consistency` — multiple paths, validation
  - `ire` — iterative refinement
  - `reasoning-agent` — general systematic reasoning
  - `consistency-agent` — contradiction detection
  - `ReflexionAgent` — self-reflection, bias detection
  - `GKPAgent` — cross-domain knowledge synthesis

### Tier 3: Multi-Agent Swarms
- Endpoint: `POST /v1/swarm/completions`
- 3 to 10,000+ agents
- Batch: `POST /v1/swarm/batch/completions` (Pro+ only)
- Config: `SwarmSpec` with `agents` array, `swarm_type`, `task`/`tasks`

## Health Check
```
GET https://api.swarms.world/health
```

## Conversation History
Include `history` parameter with previous messages:
```json
{
  "history": [
    {"role": "user", "content": "..."},
    {"role": "assistant", "content": "..."}
  ]
}
```

## Swarm-Specific Parameters
- `rearrange_flow` — for AgentRearrange type
- `rules` — governance constraints
- `messages` — for GroupChat types
- `stream` — real-time SSE output
- `heavy_swarm_loops_per_agent` — loops per agent in HeavySwarm
- `heavy_swarm_question_agent_model_name` — question agent model
- `heavy_swarm_worker_model_name` — worker model

## Choosing Architecture

**Sequential** when: ordered pipeline, each step depends on previous
**Concurrent** when: independent parallel tasks, speed matters
**MixtureOfAgents** when: need multiple specialist domains
**HierarchicalSwarm** when: complex org structure, delegation chains
**MajorityVoting** when: consensus/validation decisions
**GroupChat** when: collaborative brainstorming
**MultiAgentRouter** when: intelligent task routing at scale
**auto** when: unsure, let the system decide


path: references/atp-protocol.md
content: # ATP — Agent Trade Protocol

Payment settlement system for AI agent services on Solana blockchain. Automatic payment processing based on token usage.

## Components
1. **Settlement Service (Facilitator)** — handles usage parsing, payment calculation, blockchain transactions
   - URL: `https://facilitator.swarms.world`
2. **Middleware** — FastAPI middleware intercepting API responses, encrypting until payment confirmed
3. **Client** — user-facing client for ATP-protected endpoints

## Request Flow
1. Client sends request with wallet private key in header
2. Endpoint processes, returns response with usage data
3. Middleware encrypts response, sends payment request
4. Settlement service calculates cost, creates split transaction on Solana
5. After on-chain confirmation, response is decrypted and returned

## Payment Splitting
- **Treasury:** 5% (default processing fee)
- **Recipient:** 95% (endpoint host's wallet)

## Server Setup

```python
from fastapi import FastAPI
from atp.middleware import ATPSettlementMiddleware
from atp.schemas import PaymentToken

app = FastAPI()
app.add_middleware(
    ATPSettlementMiddleware,
    allowed_endpoints=["/v1/chat"],
    input_cost_per_million_usd=10.0,
    output_cost_per_million_usd=30.0,
    recipient_pubkey="YourSolanaWallet",
    payment_token=PaymentToken.SOL,
    wallet_private_key_header="x-wallet-private-key",
    require_wallet=True,
    settlement_service_url="https://facilitator.swarms.world",
    settlement_timeout=300.0,
    fail_on_settlement_error=False,
)
```

## Client Usage

```python
from atp.client import ATPClient

client = ATPClient(
    wallet_private_key="[1,2,3,...]",
    settlement_service_url="https://facilitator.swarms.world"
)

response = await client.post(
    url="https://api.example.com/v1/chat",
    json={"message": "Hello!"}
)
```

## Supported Usage Formats
- OpenAI: `usage.prompt_tokens` / `completion_tokens`
- Anthropic: `usage.input_tokens` / `output_tokens`
- Google/Gemini: `usageMetadata.promptTokenCount` / `candidatesTokenCount`
- Nested formats auto-detected

## Response Fields (added by middleware)
- `atp_usage` — normalized token counts
- `atp_settlement` — transaction signature, pricing, payment breakdown
- `atp_settlement_status` — "paid" | "failed"

## Environment Variables
- `ATP_SETTLEMENT_URL` — facilitator URL
- `ATP_SETTLEMENT_TIMEOUT` — timeout seconds (default 300)
- `ATP_ENCRYPTION_KEY` — Fernet key for response encryption

## Best Practices
- Never log/persist wallet private keys
- Use `fail_on_settlement_error=False` for graceful degradation
- Increase timeout for blockchain confirmation delays
- Include accurate token counts in responses
- Test with testnet wallets first


path: references/marketplace.md
content: # Swarms Marketplace

World's largest AI agent marketplace — discover, share, and monetize agents and prompts.

## Publishing

### Product Types
- **Agents** — executable code with full capabilities
- **Prompts** — template-based, reusable prompt configurations
- **Tools** — utility functions for agent enhancement

### APIs
- **Agents API:** Create, update, query agents programmatically
- **Prompts API:** Manage and discover prompt templates
- **Launch:** [swarms.world/launch](https://swarms.world/launch)

### Monetization Models
1. **Free** — build reputation and user base
2. **Paid** — fixed USD price, one-time purchase
3. **Tokenized** — tradeable assets on Solana with ongoing revenue

### Creator Fees
- 0.5% on all buy/sell transactions for listed products

## Token Launch API

**POST** `https://swarms.world/api/token/launch`

Creates agent listing + launches Solana token in single request.

### Required Fields
| Field | Type | Description |
|-------|------|-------------|
| `name` | string | Agent display name (min 2 chars) |
| `description` | string | Agent description |
| `ticker` | string | Token symbol (1-10 chars, letters+numbers) |
| `private_key` | string | Solana wallet key (JSON array, base64, or base58) |

### Optional
| Field | Type | Description |
|-------|------|-------------|
| `image` | string/file | URL, base64, or multipart file upload |

### Response
```json
{
  "success": true,
  "id": "uuid",
  "listing_url": "https://swarms.world/agent/{id}",
  "tokenized": true,
  "token_address": "7xKX...",
  "pool_address": "9yZ..."
}
```

### Cost: ~0.04 SOL per token launch

### Auth: `[REDACTED_SECRET]`

## Marketplace Prompts

Agents can reference marketplace prompts via `marketplace_prompt_id` in their config instead of writing custom system prompts.


path: references/streaming.md
content: # Streaming Responses

Enable real-time SSE (Server-Sent Events) streaming from Swarms agents.

## Enable
Set `streaming_on: true` in agent config.

## SSE Event Types

| Event | Data | Description |
|-------|------|-------------|
| `metadata` | `{job_id, name}` | Job info at start |
| `chunk` | `{content}` | Incremental text |
| `usage` | `{tokens_used, cost}` | Token/cost summary |
| `done` | `{status}` | Completion signal |
| `error` | `{error}` | Error details |

## Python Example

```python
headers = {
    "x-api-key": API_KEY,
    "Content-Type": "application/json",
    "Connection": "keep-alive",
    "X-Accel-Buffering": "no"
}

payload = {
    "agent_config": {
        "agent_name": "StreamAgent",
        "model_name": "claude-sonnet-4-20250514",
        "max_tokens": 8192,
        "streaming_on": True
    },
    "task": "Your task"
}

response = requests.post(
    f"{BASE_URL}/v1/agent/completions",
    headers=headers, json=payload, stream=True
)

for line in response.iter_lines():
    line = line.decode("utf-8")
    if line.startswith("event: "):
        current_event = line[7:].strip()
    elif line.startswith("data: "):
        data = json.loads(line[6:])
        if current_event == "chunk":
            print(data.get("content", ""), end="", flush=True)
```

## Multi-Agent Streaming
Set `"stream": true` in SwarmSpec (top-level, not per-agent).


path: references/sub-agents.md
content: # Sub-Agent Delegation

Enables a coordinator agent to dynamically spawn and delegate to specialized child agents at runtime.

## Requirements
- `max_loops`: `"auto"` (enables autonomous agent loop)
- `selected_tools`: `"all"` or include `"create_sub_agent"` and `"assign_task"`
- Uses standard `/v1/agent/completions` endpoint

## Flow
1. Coordinator analyzes task → plans sub-agents needed
2. Calls `create_sub_agent` with agent specs
3. Calls `assign_task` to distribute work (concurrent execution)
4. Results aggregated → coordinator compiles final output

## create_sub_agent Tool

```json
{
  "agents": [
    {
      "agent_name": "unique-name",
      "agent_description": "Role and capabilities",
      "system_prompt": "Optional custom instructions"
    }
  ]
}
```
Each sub-agent gets ID: `sub-agent-{uuid}`

## assign_task Tool

```json
{
  "assignments": [
    {
      "agent_id": "sub-agent-a1b2c3d4",
      "task": "Specific task description",
      "task_id": "optional-task-id"
    }
  ],
  "wait_for_completion": true
}
```
- `wait_for_completion: true` (default) — waits for all results
- `wait_for_completion: false` — fire-and-forget

## Example

```python
payload = {
    "agent_config": {
        "agent_name": "Research-Coordinator",
        "description": "Coordinates parallel research",
        "system_prompt": "You are a research coordinator. Create sub-agents for each domain and delegate tasks.",
        "model_name": "gpt-4.1",
        "max_loops": "auto",
        "max_tokens": 8192,
        "temperature": 0.3
    },
    "task": "Research quantum computing across hardware, software, and commercial applications."
}
```

## Available Internal Tools (when max_loops="auto")
- `create_plan` — planning
- `think` — reasoning
- `subtask_done` — mark subtask complete
- `complete_task` — mark task complete
- `respond_to_user` — send response
- `create_file` / `update_file` / `read_file` / `list_directory` / `delete_file` — file ops
- `create_sub_agent` / `assign_task` — delegation
- `run_bash` — NOT permitted (security)


path: references/tools.md
content: # Tools Integration

Extend agent capabilities with custom tool definitions using OpenAPI-style function specs.

## Defining Tools

```python
tools = [
    {
        "type": "function",
        "function": {
            "name": "search_topic",
            "description": "Search for information on a topic",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Search query"
                    },
                    "depth": {
                        "type": "integer",
                        "description": "Search depth (1-3)"
                    }
                },
                "required": ["query"]
            }
        }
    }
]
```

## Usage in Agent Config

```python
payload = {
    "agent_config": {
        "agent_name": "ToolAgent",
        "system_prompt": "You have access to search tools...",
        "model_name": "gpt-4o",
        "tools_list_dictionary": tools,
        "max_loops": 1
    },
    "task": "Research AI trends"
}
```

## MCP (Model Context Protocol) Integration

Connect agents to MCP servers for extended tool access:

```python
# Single MCP server
"mcp_url": "https://your-mcp-server.com"

# Or with config
"mcp_config": {
    "url": "https://your-mcp-server.com",
    "headers": {"Authorization": "Bearer ..."}
}

# Multiple MCP servers
"mcp_configs": {
    "servers": [
        {"url": "https://mcp1.com"},
        {"url": "https://mcp2.com"}
    ]
}
```

## Selected Tools (Autonomous Mode)

When `max_loops="auto"`, restrict available tools:

```python
"selected_tools": ["think", "create_plan", "create_sub_agent", "assign_task"]
```

Available: `create_plan`, `think`, `subtask_done`, `complete_task`, `respond_to_user`, `create_file`, `update_file`, `read_file`, `list_directory`, `delete_file`, `create_sub_agent`, `assign_task`

NOT available: `run_bash` (security restriction)


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: suspicious | SkillSpector: suspicious (CRITICAL)