> ## 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.

# Multi-Agent Overview

> Comprehensive guide to multi-agent systems, swarm types, best practices, and the Swarm Completions API endpoint

The Swarms API provides powerful multi-agent orchestration capabilities, enabling you to build complex systems where multiple AI agents collaborate to solve problems. Each multi-agent architecture type is designed for specific use cases and can be combined to create powerful multi-agent systems.

## Swarm Completions Endpoint

The `/v1/swarm/completions` endpoint is the primary API for executing multi-agent swarm workflows. This endpoint supports both standard and streaming responses, allowing you to orchestrate complex multi-agent systems.

**Endpoint**: `POST /v1/swarm/completions`

**Base URL**: `https://api.swarms.world`

### Authentication

All requests require an API key in the header:

```
x-api-key: your_api_key_here
```

### Input Parameters

The request body uses the `SwarmSpec` schema. All parameters are organized in the tables below:

#### Swarm Configuration Parameters

| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `name` | `string` | No | - | The name of the swarm, which serves as an identifier for the group of agents and their collective task. Maximum length: 100 characters. |
| `description` | `string` | No | - | A comprehensive description of the swarm's objectives, capabilities, and intended outcomes. |
| `swarm_type` | `string` | No | - | The classification of the swarm, indicating its operational style and methodology. One of 14 values — see [Available Architectures](/docs/documentation/multi-agent/available-architectures). |
| `max_loops` | `integer` | No | `1` | The maximum number of execution loops allowed for the swarm, enabling repeated processing if needed. **At most 50** — exceeding it returns a `422`. |
| `task` | `string` | No | - | The specific task or objective that the swarm is designed to accomplish. At least one of `task`, `tasks`, or `messages` is required. |
| `tasks` | `array[string]` | No | - | A list of tasks that the swarm should complete. Used for workflows that handle multiple tasks. |
| `agents` | `array[AgentSpec]` | No | - | A list of agents or specifications that define the agents participating in the swarm. **At most 2000** — exceeding it returns a `422`. Required for every `swarm_type` except `HeavySwarm`, which can build its own team. See Agent Configuration table below. |
| `rearrange_flow` | `string` | No | - | Instructions on how to rearrange the flow of tasks among agents, if applicable. Used with `AgentRearrange` swarm type. |
| `messages` | `array[object] \| object` | No | - | A list of messages or a message object that the swarm should process. Used for conversational workflows like `GroupChat`. |
| `img` | `string` | No | - | An optional image URL that may be associated with the swarm's task or representation. |
| `stream` | `boolean` | No | `false` | A flag indicating whether the swarm should stream its output in real-time. |
| `multi_agent_collab_prompt` | `boolean` | No | `true` | Inject the multi-agent collaboration prompt so agents coordinate with one another. Set to `false` to disable. |
| `list_all_agents` | `boolean` | No | `false` | Whether to list all agents and their descriptions to one another so each agent is aware of the others. |
| `heavy_swarm_question_agent_model_name` | `string` | No | `"gpt-5.4"` | For `HeavySwarm`: the model name to use for the question agent. |
| `heavy_swarm_worker_model_name` | `string` | No | `"claude-sonnet-4-20250514"` | For `HeavySwarm`: the model name to use for the worker agent. |
| `heavy_swarm_max_loops` | `integer` | No | `1` | For `HeavySwarm`: the maximum number of loops each agent in the heavy swarm may run. |
| `heavy_swarm_variant` | `string` | No | `"default"` | For `HeavySwarm`: which agent variant to run. One of `"default"`, `"medium"`, or `"heavy"`. |
| `council_judge_model_name` | `string` | No | `"gpt-5.4"` | For `CouncilAsAJudge`: the model name used by the judge that delivers the final ruling. |
| `chairman_model` | `string` | No | `"gpt-5.1"` | For `LLMCouncil`: the model name used by the chairman that synthesizes the council's responses. |
| `director_model_name` | `string` | No | `"gpt-5.4"` | The model name used by the director/overseer agent. For `HierarchicalSwarm`, this is the model that decomposes the task and delegates to workers. |
| `director_settings` | `object` | No | `{}` | Optional settings for the director agent, such as `temperature`, `top_p`, and `max_tokens`. For `HierarchicalSwarm`, these tune the director's planning behavior. |

#### Agent Configuration Parameters (AgentSpec)

Each agent in the `agents` array can be configured with the following parameters:

| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `agent_name` | `string` | No | - | The unique name assigned to the agent, which identifies its role and functionality within the swarm. |
| `description` | `string` | No | - | A detailed explanation of the agent's purpose, capabilities, and any specific tasks it is designed to perform. |
| `system_prompt` | `string` | No | - | The initial instruction or context provided to the agent, guiding its behavior and responses during execution. |
| `marketplace_prompt_id` | `string` | No | - | The ID of a prompt from the Swarms marketplace to use as the system prompt. If provided, the prompt will be automatically retrieved from the marketplace. |
| `model_name` | `string` | No | `"claude-sonnet-5"` | The name of the AI model that the agent will utilize for processing tasks and generating outputs. Examples: `gpt-4o`, `gpt-4.1`, `openai/o3-mini`, `claude-sonnet-4-20250514`. |
| `auto_generate_prompt` | `boolean` | No | `false` | A flag indicating whether the agent should automatically create prompts based on the task requirements. |
| `max_tokens` | `integer` | No | `16000` | The maximum number of tokens that the agent is allowed to generate in its responses, limiting output length. Values below 1 are rejected with a 422 validation error. |
| `temperature` | `number` | No | - | A parameter that controls the randomness of the agent's output; lower values result in more deterministic responses. If omitted, no temperature is sent to the model and the provider's own default applies. |
| `role` | `string` | No | `"worker"` | The designated role of the agent within the swarm, which influences its behavior and interaction with other agents. |
| `max_loops` | `integer \| string` | No | `1` | Maximum number of iterations the agent can perform for its task. Accepts an integer of 1 or greater for a fixed count, or `'auto'` to allow the system to determine the necessary number based on the task's complexity. Integer values below 1 are rejected with a 422 validation error. |
| `tools_list_dictionary` | `array[object]` | No | - | A dictionary of tools that the agent can use to complete its task. |
| `selected_tools` | `string \| array[string]` | No | All safe tools | Tools to enable for the autonomous looper when `max_loops="auto"`. Pass a list of tool names to restrict which tools the agent can use (e.g. `["think", "create_plan"]`). Available tools: `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`. Note: `run_bash` is not permitted for security reasons. |
| `mcp_url` | `string` | No | - | The URL of the MCP server that the agent can use to complete its task. |
| `mcp_config` | `object` | No | - | The MCP connection configuration to use for the agent. See MCP Connection Configuration table below. |
| `mcp_configs` | `object` | No | - | Multiple MCP connections to use for the agent. This is a list of MCP connections. See Multiple MCP Connections below. |
| `streaming_on` | `boolean` | No | `false` | A flag indicating whether the agent should stream its output. |
| `llm_args` | `object` | No | - | Additional arguments to pass to the LLM such as `top_p`, `frequency_penalty`, `presence_penalty`, etc. |
| `dynamic_temperature_enabled` | `boolean` | No | `false` | A flag indicating whether the agent should dynamically adjust its temperature based on the task. |
| `tool_call_summary` | `boolean` | No | `true` | A parameter enabling an agent to summarize tool calls. |
| `reasoning_effort` | `string` | No | - (unset) | The effort to put into reasoning, tracking the reasoning levels the installed litellm advertises. Options: `'minimal'`, `'low'`, `'medium'`, `'high'`, `'none'`, `'xhigh'`, `'ultra'`, `'max'`. `'max'` is the deepest tier and needs no beta header. At `'xhigh'` and above, pair with a large `max_tokens` so the model has room to think and answer. |
| `thinking_tokens` | `integer` | No | - | The number of tokens to use for thinking. Used with reasoning-enabled models. |
| `reasoning_enabled` | `boolean` | No | `false` | A parameter enabling an agent to use reasoning capabilities. |
| `publish_to_marketplace` | `boolean` | No | `false` | A flag indicating whether to publish this agent to the Swarms marketplace. |
| `use_cases` | `array[object]` | No | - | A list of use case dictionaries with `title` and `description` keys. Required when `publish_to_marketplace` is `true`. |
| `tags` | `array[string]` | No | - | A list of searchable tags/keywords for the marketplace (e.g., `['finance', 'analysis']`). |
| `capabilities` | `array[string]` | No | - | A list of agent capabilities or features (e.g., `['trend-analysis', 'risk-assessment']`). |
| `category` | `string` | No | - | The marketplace category for the agent (e.g., `'research'`, `'content'`, `'coding'`, `'finance'`, `'healthcare'`, `'education'`, `'legal'`). |
| `is_free` | `boolean` | No | `true` | A flag indicating whether the agent is free to use in the marketplace. |
| `price_usd` | `number` | No | - | The price in USD for using this agent in the marketplace (if not free). |
| `handoffs` | `array[AgentSpec]` | No | - | A list of agent specifications that this agent can hand off tasks to. These agents will be created and passed to the agent's handoffs parameter. |

#### MCP Connection Configuration Parameters

| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `type` | `string` | No | `"mcp"` | The type of connection, defaults to `'mcp'`. |
| `url` | `string` | No | `"http://localhost:8000/mcp"` | The URL endpoint for the MCP server. |
| `tool_configurations` | `object` | No | - | Dictionary containing configuration settings for MCP tools. |
| `authorization_token` | `string` | No | - | Authentication token for accessing the MCP server. |
| `transport` | `string` | No | `"streamable_http"` | The transport protocol to use for the MCP server. |
| `headers` | `object` | No | - | Headers to send to the MCP server. |
| `timeout` | `integer` | No | `30` | Request timeout for the MCP server, in seconds. |

#### Multiple MCP Connections

| Parameter | Type | Required | Default | Description |
| - | - | - | - | - |
| `connections` | `array[MCPConnection]` | Yes | - | List of MCP connections. Each connection follows the MCP Connection Configuration schema above. |

### Output Parameters

The endpoint returns a `SwarmCompletion` object with the following parameters:

| Parameter | Type | Description |
| - | - | - |
| `job_id` | `string` | The unique identifier for the swarm completion. |
| `status` | `string` | The status of the swarm completion. |
| `swarm_name` | `string` | The name of the swarm. |
| `description` | `string` | The description of the swarm. |
| `swarm_type` | `string` | The type of the swarm. |
| `output` | `any` | The output of the swarm. Can be a string, array, or object depending on the swarm type — every architecture runs through a `SwarmRouter` with `output_type` forced to `"dict"` server-side, so in practice `output` is typically a list of `{"role": ..., "content": ...}` turns. |
| `number_of_agents` | `integer` | The number of agents in the swarm, counted from the request's `agents` array (`0` for `HeavySwarm` runs that supply no agents). |
| `execution_time` | `number` | The execution time of the swarm in seconds. |
| `usage` | `object` | Usage statistics including token counts and costs. |
| `tasks` | `array[string]` | Present only when the request set `tasks` — echoes it back so results can be matched to what was sent. Absent otherwise. |
| `messages` | `array[object] \| object` | Present only when the request set `messages` — echoes it back. Absent otherwise. |

## Swarm Architectures

Each multi-agent architecture type is designed for specific use cases and can be combined to create powerful multi-agent systems. There are **14** supported `swarm_type` values, exactly matching what `GET /v1/swarms/available` returns live. See [Available Architectures](/docs/documentation/multi-agent/available-architectures) for the full description, category, best-for use cases, and tuning parameters of each.

| Swarm Type | Description | Documentation |
| - | - | - |
| `AgentRearrange` | Dynamically reorganize agents to optimize task performance | [Learn More](/docs/documentation/multi-agent/agent_rearrange) |
| `MixtureOfAgents` | Combine diverse specialist agents for complex tasks | [Learn More](/docs/documentation/multi-agent/mixture_of_agents) |
| `SequentialWorkflow` | Executes tasks in a strict, predefined order | [Learn More](/docs/documentation/multi-agent/sequential_workflow) |
| `ConcurrentWorkflow` | Runs independent tasks in parallel for higher throughput | [Learn More](/docs/documentation/multi-agent/concurrent_workflow) |
| `GroupChat` | Collaborative problem-solving through conversation | [Learn More](/docs/documentation/multi-agent/group_chat) |
| `MultiAgentRouter` | Intelligent dispatcher that routes tasks based on capabilities/load | [Learn More](/docs/documentation/multi-agent/multi_agent_router) |
| `HierarchicalSwarm` | Multi-level structures with delegation and escalation | [Learn More](/docs/documentation/multi-agent/hierarchical_swarm) |
| `MajorityVoting` | Consensus-based decision-making across multiple agents | [Learn More](/docs/documentation/multi-agent/majority_voting) |
| `CouncilAsAJudge` | Council-based evaluation system | [Learn More](/docs/documentation/multi-agent/council_as_a_judge) |
| `HeavySwarm` | High-capacity swarm processing | [Learn More](/docs/documentation/multi-agent/heavy_swarm) |
| `LLMCouncil` | Language model council for decisions | [Learn More](/docs/documentation/multi-agent/llm_council) |
| `DebateWithJudge` | Structured debate with judgment | [Learn More](/docs/documentation/multi-agent/debate_with_judge) |
| `RoundRobin` | Round-robin task distribution | [Learn More](/docs/documentation/multi-agent/round_robin) |
| `PlannerWorkerSwarm` | Separates planning from execution: planner agents break the task into sub-tasks that worker agents pull from a shared queue | [Learn More](/docs/documentation/multi-agent/planner_worker_swarm) |

<Note>
  `BatchedGridWorkflow` and `GraphWorkflow` are **not** `swarm_type` values — each has its own dedicated, premium-only endpoint (`/v1/batched-grid-workflow/completions` and `/v1/graph-workflow/completions`). `"auto"` and `"SpreadSheetSwarm"` are rejected with a `400` error if sent as `swarm_type`. See [Available Architectures](/docs/documentation/multi-agent/available-architectures) for details.
</Note>

## Best Practices

This section outlines production-grade best practices for using the Swarms API effectively. These guidelines will help you choose the right swarm architecture, optimize costs, and implement robust error handling in your multi-agent systems.

### Choosing the Right Swarm Architecture

Selecting the optimal swarm architecture is crucial for achieving your desired outcomes. Start by analyzing your task complexity: complex tasks benefit from `HierarchicalSwarm` or `MultiAgentRouter`. For dynamic tasks that require adaptive processing, consider `AgentRearrange`.

When evaluating workflow patterns, use `SequentialWorkflow` for linear processes where each step depends on the previous one, `ConcurrentWorkflow` for parallel operations that can run independently, and `GroupChat` for collaborative tasks requiring interactive problem-solving. For multi-domain expertise requirements, `MixtureOfAgents` combines diverse specialist agents effectively, while `MajorityVoting` provides consensus-based decision-making for quality assurance needs.

Different applications have specific swarm recommendations. Team automation systems excel with `HierarchicalSwarm`, providing automated team coordination with clear responsibility chains and scalable structures. Research pipelines benefit from `SequentialWorkflow`, ensuring structured processes with quality control at each stage. Trading systems leverage `ConcurrentWorkflow` for multi-market coverage and real-time analysis with risk distribution. Content factories utilize `MixtureOfAgents` for automated content creation with consistent quality and high throughput.

Industry-specific patterns also guide architecture selection. In finance, risk analysis uses `HierarchicalSwarm`, market research employs `MixtureOfAgents`, and trading strategies leverage `ConcurrentWorkflow`. Healthcare applications use `SequentialWorkflow` for patient analysis, `MajorityVoting` for research review, `GroupChat` for treatment planning, and `MultiAgentRouter` for medical records management. Legal workflows apply `SequentialWorkflow` for document review, `MixtureOfAgents` for case analysis, `HierarchicalSwarm` for compliance checks, and `ConcurrentWorkflow` for contract analysis.

### Cost Optimization

Swarm completions bill a flat per-agent fee (`swarm_completions_agent_cost`, $0.01 by default) plus token costs (`swarm_completions_input_cost_per_1m` / `swarm_completions_output_cost_per_1m`, $6.50 / \$18.50 per 1M tokens by default — see [Pricing](/docs/documentation/resources/pricing) for current values). Only the token component is discounted off-peak; the per-agent fee is charged in full regardless of time.

The clearest, verifiable cost lever is timing: requests are automatically billed at a **50% discount on the token cost** when the server's clock, in the `America/Los_Angeles` timezone, falls between 8 PM and 6 AM (20:00–05:59 PT) — there is no separate "off-peak tier" to opt into; the discount applies automatically based on when the request runs. Beyond that, the usual principles apply: use only as many agents as the task needs (each one adds a flat per-agent fee), keep `max_tokens` and prompts focused on what the task requires, and pick a `max_loops` no larger than necessary — extra loops re-run the same agents and add tokens without a documented cost multiplier to justify them.

### Production Best Practices

Implementing robust production practices ensures reliable and efficient multi-agent systems. Use the swarm type suited to your task shape (see [Available Architectures](/docs/documentation/multi-agent/available-architectures)), implement error handling with retry logic for transient failures, and log responses (`job_id`, `execution_time`, `usage`) to track cost and performance over time. Check your credit balance and rate-limit headers (`X-RateLimit-*`, see [Rate Limit Headers](/docs/documentation/resources/rate-limit-headers)) rather than assuming a request will succeed.

Avoid common anti-patterns that can compromise your system's reliability and security. Never hardcode API keys in your application code — load them from the environment. Respect rate limits to prevent `429` responses, and stay above the minimum credit balance (billable routes require a total balance greater than \$1.00, or requests are rejected with `402` before any work runs). Avoid using more agents than a task requires — every agent in the `agents` array adds a flat per-agent fee whether or not its output changes the final result.

### Error Handling

The API returns standard HTTP status codes. `401` means a missing or invalid `x-api-key` — rotate and store keys securely. `402` means your credit balance is below the required minimum. `403` means the request used a model or endpoint gated to premium accounts. `422` is a validation error — the response body's `detail` array names the offending field and constraint (see the [Errors reference](/docs/documentation/multi-agent/swarm_completions#errors)); validate `max_loops` (≤ 50), `agents` length (≤ 2000), and `temperature` (0–2) client-side before sending. `429` means you exceeded a rate-limit window — back off using the `Retry-After` header. `500` is a server-side failure — retry with backoff.

## Example Usage

### Basic Swarm Completion

<Tabs>
  <Tab title="Shell (curl)">
    ```bash theme={null}
    curl -X POST "https://api.swarms.world/v1/swarm/completions" \
      -H "x-api-key: $SWARMS_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "Research Team",
        "description": "Multi-agent research swarm",
        "swarm_type": "MixtureOfAgents",
        "task": "Analyze the impact of AI on healthcare",
        "agents": [
          {
            "agent_name": "Research Analyst",
            "description": "Conducts comprehensive research",
            "system_prompt": "You are a research analyst specializing in healthcare technology.",
            "model_name": "gpt-4.1",
            "max_loops": 1,
            "temperature": 0.3
          }
        ],
        "max_loops": 1
      }'
    ```
  </Tab>

  <Tab title="Python (requests)">
    ```python theme={null}
    import os
    import requests
    from dotenv import load_dotenv

    load_dotenv()

    API_BASE_URL = "https://api.swarms.world"
    API_KEY = os.getenv("SWARMS_API_KEY")

    headers = {
        "x-api-key": API_KEY,
        "Content-Type": "application/json"
    }

    swarm_config = {
        "name": "Research Team",
        "description": "Multi-agent research swarm",
        "swarm_type": "MixtureOfAgents",
        "task": "Analyze the impact of AI on healthcare",
        "agents": [
            {
                "agent_name": "Research Analyst",
                "description": "Conducts comprehensive research",
                "system_prompt": "You are a research analyst specializing in healthcare technology.",
                "model_name": "gpt-4.1",
                "max_loops": 1,
                "temperature": 0.3
            }
        ],
        "max_loops": 1
    }

    response = requests.post(
        f"{API_BASE_URL}/v1/swarm/completions",
        headers=headers,
        json=swarm_config
    )

    result = response.json()
    print(result)
    ```
  </Tab>
</Tabs>

## Additional Resources

* [API Dashboard](https://swarms.world/platform/api-keys)
* [API Reference](https://docs.swarms.ai/api-reference)
* [Getting Started Guide](/docs/documentation/getting-started/quickstart)


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