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

# Agent Completions Reference

> Learn how to build individual agents and their capabilities with swarms

The Agent Completions endpoint (`/v1/agent/completions`) enables you to execute individual AI agents with specific tasks, configurations, and capabilities. This endpoint provides a flexible way to run single agents with various models, tools, and configurations.

## Endpoint Information

* **URL**: `/v1/agent/completions`
* **Method**: `POST`
* **Authentication**: Required (`x-api-key` header; `Authorization: Bearer <key>` is also accepted)
* **Rate Limiting**: Subject to tier-based rate limits

## Request Schema

### AgentCompletion Object

| Field | Type | Required | Description |
| - | - | - | - |
| `agent_config` | `AgentSpec` | Yes | The configuration of the agent to be completed |
| `task` | `string` | No | The task to be completed by the agent |
| `history` | `Union[Dict, List[Dict]]` | No | The history of the agent's previous tasks and responses. Can be either a dictionary or a list of message objects |
| `img` | `string` | No | A base64 encoded image for the agent to process. Encode your image file to base64 and pass it here |
| `imgs` | `List[string]` | No | A list of base64 encoded images for the agent to process. Encode your image files to base64 and pass them here |
| `tools_enabled` | `List[string]` | No | Built-in tools for the agent. Supported values: `auto_search` (web search) and `web_scraper` (web scraping). Both may be listed together, in which case the agent receives both tools. Enabling a tool is billed once per request (a flat search or scrape fee), regardless of how many times the agent uses it |

### AgentSpec Object

| Field | 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. For example: gpt-4o, gpt-4.1, openai/o3-mini |
| `fallback_models` | `List[string]` | No | - | An ordered list of models to try if the primary model errors: the request is retried with the next model on failure. **If `model_name` is omitted, the first entry of `fallback_models` becomes the primary model.** Each entry is subject to the same free-tier model restrictions as `model_name`. Example: `["gpt-4.1", "gpt-5.4"]` |
| `fallback_model_name` | `string` | No | - | A single fallback model to try, after any `fallback_models` have been exhausted |
| `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` | `float` | No | - | A parameter that controls the randomness of the agent's output; lower values result in more deterministic responses. Accepted range: 0 to 2. If omitted, no temperature is sent to the model (the provider's own default applies), and `dynamic_temperature_enabled` is forced to `false` regardless of what you pass |
| `role` | `string` | No | `"worker"` | The designated role of the agent within the swarm, which influences its behavior and interaction with other agents |
| `max_loops` | `int \| "auto"` | No | `1` | Maximum number of iterations the agent can perform for its task. Accepts an integer from 1 to 50 for a fixed count, or `"auto"` to let the agent decide when it's done. Integer values below 1 are rejected with a 422 validation error |
| `tools_list_dictionary` | `List[Dict]` | No | - | A list of OpenAI function-calling-style JSON schemas the agent can call |
| `selected_tools` | `string \| List[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`. `run_bash` is never permitted, even if you pass it explicitly |
| `mcp_url` | `string \| MCPConnection` | No | - | A single MCP server the agent can use: a bare URL string for an unauthenticated server, or an [`MCPConnection`](#mcp-connections) object for auth/transport control. This is the only MCP field that adds the MCP fee to `usage.total_cost` — see [MCP Connections](#mcp-connections) |
| `streaming_on` | `boolean` | No | `false` | A flag indicating whether the agent should stream its output over SSE. See [Streaming](#streaming) |
| `llm_args` | `Dict` | No | - | Additional arguments to pass to the LLM such as `top_p`, `frequency_penalty`, `presence_penalty`, etc. |
| `top_p` | `float` | No | - | Nucleus sampling parameter passed to the LLM. Equivalent to putting `top_p` inside `llm_args` |
| `dynamic_temperature_enabled` | `boolean` | No | `false` | A flag indicating whether the agent should dynamically adjust its temperature based on the task. Forced to `false` whenever `temperature` is omitted |
| `mcp_config` | `MCPConnection` | No | - | A single MCP connection object for the agent (like `mcp_url`, but always a full object, never a bare string) |
| `mcp_configs` | `List[MCPConnection]` | No | - | Several MCP connection objects for the agent. Tools from every server are combined |
| `mcp_urls` | `List[string \| MCPConnection]` | No | - | Several MCP servers for the agent. Each entry is a URL string for an unauthenticated server, or an `MCPConnection` object. Tools from every server are combined |
| `tool_call_summary` | `boolean` | No | `true` | A parameter enabling an agent to summarize tool calls |
| `reasoning_effort` | `string` | No | - (unset) | How much effort the agent puts into reasoning. Accepted values: `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `ultra`, `max` (`max` is the deepest tier and needs no beta header; at `xhigh` and above, pair with a large `max_tokens`). **On Claude 5-family models** (any `claude-sonnet-5`, `claude-opus-5`, `claude-haiku-5`, or `claude-fable-5` id, including point releases like `claude-sonnet-5.5`, but not 4.x ids like `claude-opus-4-8`) the API currently cannot send extended-thinking parameters to the provider: `reasoning_effort`, `reasoning_enabled`, and `thinking_tokens` are all dropped with a server-side warning, and the agent runs without extended thinking |
| `thinking_tokens` | `integer` | No | - | The number of tokens to use for thinking. Dropped on Claude 5-family models — see `reasoning_effort` above |
| `reasoning_enabled` | `boolean` | No | `false` | A parameter enabling an agent to use reasoning. Dropped on Claude 5-family models — see `reasoning_effort` above |
| `publish_to_marketplace` | `boolean` | No | `false` | A flag indicating whether to publish this agent to the Swarms marketplace |
| `use_cases` | `List[Dict[str, str]]` | No | - | A list of use case dictionaries with 'title' and 'description' keys. Required when publish\_to\_marketplace is True |
| `tags` | `List[string]` | No | - | A list of searchable tags/keywords for the marketplace (e.g., \['finance', 'analysis']) |
| `capabilities` | `List[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` | `float` | No | - | The price in USD for using this agent in the marketplace (if not free) |
| `handoffs` | `List[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 Connections

Four `AgentSpec` fields attach MCP (Model Context Protocol) servers to an agent — `mcp_url` (one server), `mcp_config` (one server, object form only), `mcp_configs` (several servers), and `mcp_urls` (several servers, string or object form). Each server's tools are added to the agent's tool set; when several servers are attached, their tools are combined.

For an unauthenticated server, a bare URL string is enough:

```json theme={null}
{ "mcp_url": "http://localhost:8000/mcp" }
```

For anything that needs authentication, a custom transport, or non-default timeouts, pass an `MCPConnection` object instead.

### MCPConnection Object

| Field | Type | Default | Description |
| - | - | - | - |
| `type` | `string` | `"mcp"` | The type of connection |
| `url` | `string` | `"http://localhost:8000/mcp"` | The URL endpoint for the MCP server |
| `name` | `string` | - | Human readable name for the server, used in logs and tool routing |
| `tool_configurations` | `Dict` | - | Per-tool configuration settings |
| `authorization_token` | `string` | - | Bearer token for accessing the MCP server |
| `api_key` | `string` | - | API key for the MCP server, sent via `api_key_header`/`api_key_prefix` |
| `api_key_header` | `string` | `"Authorization"` | Header used to send the API key, e.g. `"Authorization"` or `"X-API-Key"` |
| `api_key_prefix` | `string` | `"Bearer"` | Prefix prepended to the API key value. Set to `null`/`""` for a raw key |
| `auth_type` | `string` | - | Explicit auth mode. Inferred from the other fields when omitted |
| `oauth` | `MCPOAuthConfig` | - | OAuth 2.1 configuration for this server — see below |
| `transport` | `string` | `"streamable_http"` | Transport protocol: `"streamable_http"`, `"sse"`, `"stdio"`, or `"auto"` |
| `headers` | `Dict` | - | Extra headers to send to the MCP server |
| `timeout` | `integer` | `30` | Request timeout (seconds) for the MCP server |
| `sse_read_timeout` | `integer` | `300` | How long to wait for streamed events before giving up |
| `tool_timeout` | `integer` | `120` | How long a single tool call may run before timing out. Separate from `timeout`, which bounds HTTP requests |
| `command` | `string` | - | Executable to launch for the `"stdio"` transport |
| `args` | `List[string]` | - | Arguments passed to the `"stdio"` command |
| `env` | `Dict` | - | Environment variables for the `"stdio"` command |

### MCPOAuthConfig Object

Set `oauth` on an `MCPConnection` to authenticate against a server that requires OAuth 2.1. Three flavors are supported, selected by which fields you set:

1. **`grant_type: "authorization_code"`** (default) — the interactive browser flow from the MCP authorization spec. PKCE and RFC 7591 dynamic client registration are handled automatically, so `client_id` is optional. Tokens are cached on disk so the browser prompt only happens once.
2. **`grant_type: "client_credentials"`** — a headless machine-to-machine flow. Requires `client_id`/`client_secret`. The token endpoint is discovered from the server's `/.well-known/oauth-authorization-server` metadata unless `token_url` is given.
3. **`access_token: "..."`** — a token you already obtained elsewhere. No flow is run; the token is sent directly as a bearer credential.

| Field | Type | Default | Description |
| - | - | - | - |
| `grant_type` | `string` | `"authorization_code"` | OAuth grant to use when no static `access_token` is supplied |
| `client_id` | `string` | - | OAuth client id. Optional for `authorization_code` when the server supports dynamic client registration |
| `client_secret` | `string` | - | OAuth client secret. Required for `client_credentials` |
| `scopes` | `List[string]` | - | Scopes to request, e.g. `["mcp:tools", "offline_access"]` |
| `redirect_uri` | `string` | `"http://127.0.0.1:8765/callback"` | Loopback redirect URI used to capture the authorization code |
| `client_name` | `string` | `"Swarms Agent"` | Client name sent during dynamic client registration |
| `client_uri` | `string` | - | Client homepage sent during dynamic client registration |
| `authorization_url` | `string` | - | Explicit authorization endpoint. Discovered automatically when omitted |
| `token_url` | `string` | - | Explicit token endpoint. Discovered automatically when omitted |
| `access_token` | `string` | - | Pre-obtained access token. When set, no OAuth flow is performed |
| `refresh_token` | `string` | - | Pre-obtained refresh token, paired with `access_token` |
| `token_storage_path` | `string` | - | File used to cache OAuth tokens. Defaults to `~/.swarms/mcp_auth/<server>.json` |
| `use_token_cache` | `boolean` | `true` | Persist tokens to disk so the browser flow only runs once |
| `open_browser` | `boolean` | `true` | Open the system browser for the authorization step. When `false`, the URL is logged instead |
| `callback_timeout` | `integer` | `300` | Seconds to wait for the user to complete the browser flow |

Any string field on `MCPOAuthConfig` (and `api_key`/`authorization_token` on `MCPConnection`) may reference an environment variable instead of a literal secret, using `"env:MY_VAR"` or `"${MY_VAR}"`. This keeps credentials out of request bodies and logs:

```json theme={null}
{
  "mcp_url": {
    "url": "https://mcp.example.com/mcp",
    "api_key": "env:EXAMPLE_MCP_API_KEY",
    "api_key_header": "X-API-Key",
    "api_key_prefix": ""
  }
}
```

Client-credentials OAuth example:

```json theme={null}
{
  "mcp_url": {
    "url": "https://mcp.example.com/mcp",
    "oauth": {
      "grant_type": "client_credentials",
      "client_id": "env:EXAMPLE_MCP_CLIENT_ID",
      "client_secret": "env:EXAMPLE_MCP_CLIENT_SECRET",
      "scopes": ["mcp:tools"]
    }
  }
}
```

<Note>
  Every `AgentCompletion` request that sets `agent_config.mcp_url` is charged the MCP call fee (see the [Pricing](/docs/documentation/resources/pricing) page) in addition to token costs, whether or not the agent ends up calling an MCP tool. Attaching servers only through `mcp_config`, `mcp_configs`, or `mcp_urls` does not add this fee.
</Note>

## Response Schema

### AgentCompletionOutput Object

| Field | Type | Description |
| - | - | - |
| `job_id` | `string` | Unique identifier for the completion job |
| `success` | `boolean` | Indicates successful execution |
| `name` | `string` | Name of the executed agent |
| `description` | `string` | Agent description |
| `temperature` | `float` | Temperature setting used |
| `outputs` | `any` | Generated output from the agent |
| `usage` | `Dict` | Token usage and cost information |
| `timestamp` | `string` | ISO timestamp of completion |

### Usage Information

The response includes detailed usage metrics:

```json theme={null}
{
  "usage": {
    "input_tokens": 150,
    "output_tokens": 300,
    "total_tokens": 450,
    "img_cost": 0.25,
    "total_cost": 0.256525
  }
}
```

`img_cost` is only non-zero when the request set `img`; it does not account for `imgs`. `total_cost` is input-token cost plus output-token cost plus `img_cost`, plus the MCP fee when `agent_config.mcp_url` is set (see [MCP Connections](#mcp-connections)). See the [Pricing](/docs/documentation/resources/pricing) page for the underlying per-token and per-call rates.

## Streaming

Set `agent_config.streaming_on: true` to receive the response as Server-Sent Events (`text/event-stream`) instead of a single JSON body. The HTTP status and headers are sent immediately; the connection stays open until the run finishes. Billing and logging happen once, after the run completes — streaming does not change what you're charged.

Events are emitted in this order:

1. An initial `data:` frame with no `event:` line, carrying job metadata: `job_id`, `success`, `name`, `description`, `temperature`, `timestamp`, `stream: true`, `type: "metadata"`.
2. `event: start` — `data: {"message": "Starting agent processing..."}`
3. `event: chunk` — one per generated token, `data: {"content": "<token>", "timestamp": "..."}`. Repeats until the agent finishes.
4. `event: usage` — `data:` the same usage object described above.
5. `event: end` — `data: {"job_id": ..., "usage": {...}, "timestamp": ..., "complete": true}`
6. `event: done` — `data: {"message": "Agent processing complete"}`

If the run fails at any point, the stream instead emits a single `event: error` frame — `data: {"error": "AgentCompletionError: ...", "timestamp": "..."}` — and closes without a `done` event.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import json
    import requests

    payload = {
        "agent_config": {
            "agent_name": "Streaming Agent",
            "model_name": "gpt-4.1-mini",
            "max_tokens": 1024,
            "streaming_on": True
        },
        "task": "Write a haiku about distributed systems"
    }

    with requests.post(
        "https://api.swarms.world/v1/agent/completions",
        headers={"x-api-key": "your-api-key"},
        json=payload,
        stream=True,
    ) as response:
        event = None
        for line in response.iter_lines(decode_unicode=True):
            if not line:
                continue
            if line.startswith("event:"):
                event = line.removeprefix("event:").strip()
            elif line.startswith("data:"):
                data = json.loads(line.removeprefix("data:").strip())
                if event == "chunk":
                    print(data["content"], end="", flush=True)
                elif event == "usage":
                    print("\n\nusage:", data)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const response = await fetch('https://api.swarms.world/v1/agent/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-api-key': 'your-api-key'
        },
        body: JSON.stringify({
            agent_config: {
                agent_name: "Streaming Agent",
                model_name: "gpt-4.1-mini",
                max_tokens: 1024,
                streaming_on: true
            },
            task: "Write a haiku about distributed systems"
        })
    });

    const reader = response.body!.getReader();
    const decoder = new TextDecoder();
    let event: string | null = null;
    let buffer = "";

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });

        let lineEnd: number;
        while ((lineEnd = buffer.indexOf("\n")) >= 0) {
            const line = buffer.slice(0, lineEnd).trim();
            buffer = buffer.slice(lineEnd + 1);
            if (!line) continue;
            if (line.startsWith("event:")) {
                event = line.slice(6).trim();
            } else if (line.startsWith("data:")) {
                const data = JSON.parse(line.slice(5).trim());
                if (event === "chunk") process.stdout.write(data.content);
                if (event === "usage") console.log("\nusage:", data);
            }
        }
    }
    ```
  </Tab>
</Tabs>

## Features and Capabilities

### 1. Multi-Model Support

* **OpenAI Models**: gpt-4.1, gpt-4.1-mini, gpt-4o
* **Anthropic Models**: claude-sonnet-4-20250514
* **Custom Models**: Any model supported by LiteLLM
* **Vision Models**: Support for image analysis with gpt-4.1 and compatible models

### 2. Vision Capabilities

* Single image analysis via `img` parameter
* Multiple image analysis via `imgs` parameter
* Automatic image token counting and cost calculation

### 3. Conversation History

* Maintain context across multiple interactions
* Support for both dictionary and list-based history formats
* Automatic history formatting and token counting

### 4. Tool Integration

* Enable built-in tools via `tools_enabled` parameter (`auto_search`, `web_scraper`)
* MCP (Model Context Protocol) server integration
* Custom tool dictionaries via `tools_list_dictionary`
* Tool call summarization

### 5. Advanced Configuration

* Dynamic temperature adjustment
* Custom LLM arguments (top\_p, frequency\_penalty, presence\_penalty)
* Streaming output support
* Auto-prompt generation

## Examples

### Basic Agent Execution

A simple example demonstrating how to execute a single agent with basic configuration. This example shows the minimum required fields to run an agent completion.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import requests

    payload = {
        "agent_config": {
            "agent_name": "Research Analyst",
            "description": "Expert in analyzing and synthesizing research data",
            "system_prompt": "You are a Research Analyst with expertise in data analysis and synthesis.",
            "model_name": "gpt-4.1-mini",
            "max_tokens": 8192,
            "temperature": 0.7
        },
        "task": "Analyze the impact of artificial intelligence on healthcare"
    }

    response = requests.post(
        "https://api.swarms.world/v1/agent/completions",
        headers={"x-api-key": "your-api-key"},
        json=payload
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const payload = {
        agent_config: {
            agent_name: "Research Analyst",
            description: "Expert in analyzing and synthesizing research data",
            system_prompt: "You are a Research Analyst with expertise in data analysis and synthesis.",
            model_name: "gpt-4.1-mini",
            max_tokens: 8192,
            temperature: 0.7
        },
        task: "Analyze the impact of artificial intelligence on healthcare"
    };

    const response = await fetch('https://api.swarms.world/v1/agent/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-api-key': 'your-api-key'
        },
        body: JSON.stringify(payload)
    });

    const result = await response.json();
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use reqwest;
    use serde_json::json;

    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        let client = reqwest::Client::new();
        
        let payload = json!({
            "agent_config": {
                "agent_name": "Research Analyst",
                "description": "Expert in analyzing and synthesizing research data",
                "system_prompt": "You are a Research Analyst with expertise in data analysis and synthesis.",
                "model_name": "gpt-4.1-mini",
                "max_tokens": 8192,
                "temperature": 0.7
            },
            "task": "Analyze the impact of artificial intelligence on healthcare"
        });

        let response = client
            .post("https://api.swarms.world/v1/agent/completions")
            .header("x-api-key", "your-api-key")
            .json(&payload)
            .send()
            .await?;

        let result: serde_json::Value = response.json().await?;
        println!("{:?}", result);
        
        Ok(())
    }
    ```
  </Tab>
</Tabs>

### Agent with Conversation History

This example demonstrates how to provide conversation history to maintain context across multiple interactions. The history can be provided as a dictionary or list format.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    payload = {
        "agent_config": {
            "agent_name": "Medical Assistant",
            "system_prompt": "You are a medical information assistant.",
            "model_name": "gpt-4.1-mini",
            "max_tokens": 4096
        },
        "task": "What are the symptoms of diabetes?",
        "history": {
            "message1": {
                "role": "user",
                "content": "Tell me about diabetes"
            },
            "message2": {
                "role": "assistant", 
                "content": "Diabetes is a chronic condition affecting blood sugar levels."
            }
        }
    }
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const payload = {
        agent_config: {
            agent_name: "Medical Assistant",
            system_prompt: "You are a medical information assistant.",
            model_name: "gpt-4.1-mini",
            max_tokens: 4096
        },
        task: "What are the symptoms of diabetes?",
        history: {
            message1: {
                role: "user",
                content: "Tell me about diabetes"
            },
            message2: {
                role: "assistant",
                content: "Diabetes is a chronic condition affecting blood sugar levels."
            }
        }
    };
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use serde_json::json;

    let payload = json!({
        "agent_config": {
            "agent_name": "Medical Assistant",
            "system_prompt": "You are a medical information assistant.",
            "model_name": "gpt-4.1-mini",
            "max_tokens": 4096
        },
        "task": "What are the symptoms of diabetes?",
        "history": {
            "message1": {
                "role": "user",
                "content": "Tell me about diabetes"
            },
            "message2": {
                "role": "assistant",
                "content": "Diabetes is a chronic condition affecting blood sugar levels."
            }
        }
    });
    ```
  </Tab>
</Tabs>

### Agent with Search Capabilities

Enable web search functionality for your agent by including `auto_search` in the `tools_enabled` parameter. This allows the agent to search the web for real-time information to complete tasks. Alternatively, pass `web_scraper` to let the agent scrape and format web pages. Both tools can be listed together, in which case the agent receives both and each is billed its own flat fee.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    payload = {
        "agent_config": {
            "agent_name": "Research Assistant",
            "description": "Research assistant with web search capabilities",
            "system_prompt": "You are a research assistant that can search the web.",
            "model_name": "gpt-4.1-mini",
            "max_tokens": 8192
        },
        "task": "Find the latest developments in quantum computing",
        "tools_enabled": ["auto_search"]
    }
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const payload = {
        agent_config: {
            agent_name: "Research Assistant",
            description: "Research assistant with web search capabilities",
            system_prompt: "You are a research assistant that can search the web.",
            model_name: "gpt-4.1-mini",
            max_tokens: 8192
        },
        task: "Find the latest developments in quantum computing",
        tools_enabled: ["auto_search"]
    };
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use serde_json::json;

    let payload = json!({
        "agent_config": {
            "agent_name": "Research Assistant",
            "description": "Research assistant with web search capabilities",
            "system_prompt": "You are a research assistant that can search the web.",
            "model_name": "gpt-4.1-mini",
            "max_tokens": 8192
        },
        "task": "Find the latest developments in quantum computing",
        "tools_enabled": ["auto_search"]
    });
    ```
  </Tab>
</Tabs>

### Agent with MCP Integration

Integrate Model Context Protocol (MCP) servers to extend your agent's capabilities. This example shows how to connect an agent to an unauthenticated MCP server for additional tools and resources. For authenticated servers, multiple servers, and OAuth, see [MCP Connections](#mcp-connections).

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    payload = {
        "agent_config": {
            "agent_name": "Data Analyst",
            "description": "Data analyst with database access",
            "system_prompt": "You are a data analyst with access to databases.",
            "model_name": "gpt-4.1-mini",
            "max_tokens": 8192,
            "mcp_url": "http://github.com/mcp"
        },
        "task": "Query the customer database for recent orders"
    }
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const payload = {
        agent_config: {
            agent_name: "Data Analyst",
            description: "Data analyst with database access",
            system_prompt: "You are a data analyst with access to databases.",
            model_name: "gpt-4.1-mini",
            max_tokens: 8192,
            mcp_url: "http://github.com/mcp"
        },
        task: "Query the customer database for recent orders"
    };
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use serde_json::json;

    let payload = json!({
        "agent_config": {
            "agent_name": "Data Analyst",
            "description": "Data analyst with database access",
            "system_prompt": "You are a data analyst with access to databases.",
            "model_name": "gpt-4.1-mini",
            "max_tokens": 8192,
            "mcp_url": "http://github.com/mcp"
        },
        "task": "Query the customer database for recent orders"
    });
    ```
  </Tab>
</Tabs>

### Agent with Custom LLM Arguments

Customize advanced LLM parameters such as `top_p`, `frequency_penalty`, and `presence_penalty` to fine-tune the model's behavior. This is useful for controlling creativity, repetition, and topic diversity.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    payload = {
        "agent_config": {
            "agent_name": "Creative Writer",
            "description": "Creative writing specialist",
            "system_prompt": "You are a creative writing expert.",
            "model_name": "gpt-4.1",
            "max_tokens": 2048,
            "temperature": 0.9,
            "llm_args": {
                "top_p": 0.9,
                "frequency_penalty": 0.1,
                "presence_penalty": 0.1
            }
        },
        "task": "Write a creative story about time travel"
    }
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const payload = {
        agent_config: {
            agent_name: "Creative Writer",
            description: "Creative writing specialist",
            system_prompt: "You are a creative writing expert.",
            model_name: "gpt-4.1",
            max_tokens: 2048,
            temperature: 0.9,
            llm_args: {
                top_p: 0.9,
                frequency_penalty: 0.1,
                presence_penalty: 0.1
            }
        },
        task: "Write a creative story about time travel"
    };
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use serde_json::json;

    let payload = json!({
        "agent_config": {
            "agent_name": "Creative Writer",
            "description": "Creative writing specialist",
            "system_prompt": "You are a creative writing expert.",
            "model_name": "gpt-4.1",
            "max_tokens": 2048,
            "temperature": 0.9,
            "llm_args": {
                "top_p": 0.9,
                "frequency_penalty": 0.1,
                "presence_penalty": 0.1
            }
        },
        "task": "Write a creative story about time travel"
    });
    ```
  </Tab>
</Tabs>

### Agent with Structured Outputs

Use `tools_list_dictionary` to give the agent one or more OpenAI function-calling-style JSON schemas. The agent responds with structured tool calls that conform to your schema instead of free-form text — ideal for extraction, classification, and any workflow where downstream code parses the result.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    payload = {
        "agent_config": {
            "agent_name": "Invoice Extractor",
            "description": "Extracts structured invoice data from raw text",
            "system_prompt": "You extract invoice fields from documents. Always respond using the provided tool schema.",
            "model_name": "gpt-4o",
            "max_tokens": 1024,
            "temperature": 0.1,
            "tools_list_dictionary": [
                {
                    "type": "function",
                    "function": {
                        "name": "extract_invoice",
                        "description": "Extract structured fields from an invoice",
                        "parameters": {
                            "type": "object",
                            "properties": {
                                "vendor": {"type": "string", "description": "Vendor or supplier name"},
                                "invoice_number": {"type": "string", "description": "Invoice identifier"},
                                "total_amount": {"type": "number", "description": "Total amount due in USD"},
                                "due_date": {"type": "string", "description": "Payment due date, ISO 8601"}
                            },
                            "required": ["vendor", "invoice_number", "total_amount"]
                        }
                    }
                }
            ]
        },
        "task": "Invoice ACME-2024-001 from Acme Corp: total $4,250.00, due 2026-08-01"
    }
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const payload = {
        agent_config: {
            agent_name: "Invoice Extractor",
            description: "Extracts structured invoice data from raw text",
            system_prompt: "You extract invoice fields from documents. Always respond using the provided tool schema.",
            model_name: "gpt-4o",
            max_tokens: 1024,
            temperature: 0.1,
            tools_list_dictionary: [
                {
                    type: "function",
                    function: {
                        name: "extract_invoice",
                        description: "Extract structured fields from an invoice",
                        parameters: {
                            type: "object",
                            properties: {
                                vendor: { type: "string", description: "Vendor or supplier name" },
                                invoice_number: { type: "string", description: "Invoice identifier" },
                                total_amount: { type: "number", description: "Total amount due in USD" },
                                due_date: { type: "string", description: "Payment due date, ISO 8601" }
                            },
                            required: ["vendor", "invoice_number", "total_amount"]
                        }
                    }
                }
            ]
        },
        task: "Invoice ACME-2024-001 from Acme Corp: total $4,250.00, due 2026-08-01"
    };
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use serde_json::json;

    let payload = json!({
        "agent_config": {
            "agent_name": "Invoice Extractor",
            "description": "Extracts structured invoice data from raw text",
            "system_prompt": "You extract invoice fields from documents. Always respond using the provided tool schema.",
            "model_name": "gpt-4o",
            "max_tokens": 1024,
            "temperature": 0.1,
            "tools_list_dictionary": [
                {
                    "type": "function",
                    "function": {
                        "name": "extract_invoice",
                        "description": "Extract structured fields from an invoice",
                        "parameters": {
                            "type": "object",
                            "properties": {
                                "vendor": {"type": "string", "description": "Vendor or supplier name"},
                                "invoice_number": {"type": "string", "description": "Invoice identifier"},
                                "total_amount": {"type": "number", "description": "Total amount due in USD"},
                                "due_date": {"type": "string", "description": "Payment due date, ISO 8601"}
                            },
                            "required": ["vendor", "invoice_number", "total_amount"]
                        }
                    }
                }
            ]
        },
        "task": "Invoice ACME-2024-001 from Acme Corp: total $4,250.00, due 2026-08-01"
    });
    ```
  </Tab>
</Tabs>

The agent's `outputs` content contains the structured tool call. The `function.arguments` field arrives as a JSON string, so parse it before use:

```python theme={null}
import json

result = response.json()
tool_calls = result["outputs"][-1]["content"]
invoice = json.loads(tool_calls[0]["function"]["arguments"])
print(invoice["vendor"], invoice["total_amount"])
```

<Note>
  For schema-enforced plain-JSON responses without tool calls, you can alternatively pass `response_format` inside `llm_args`. See [Structured Outputs](/docs/examples/examples/structured-outputs) for a comparison of both approaches.
</Note>

### Agent with Max Loops

Control the number of execution iterations your agent performs using the `max_loops` parameter. This is useful for tasks that require multiple reasoning steps or iterative problem-solving. Set `max_loops` to a higher value (e.g., 3-5) for complex tasks that need multiple passes, or use `"auto"` for fully autonomous agents that decide when to stop.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    payload = {
        "agent_config": {
            "agent_name": "Problem Solver",
            "description": "Agent that performs iterative problem-solving",
            "system_prompt": "You are a problem-solving agent that breaks down complex tasks into steps and iteratively refines solutions.",
            "model_name": "gpt-4.1",
            "max_loops": 3,
            "max_tokens": 4096,
            "temperature": 0.7
        },
        "task": "Solve this multi-step problem: First, research the current state of renewable energy. Then, identify the top 3 challenges. Finally, propose solutions for each challenge."
    }

    response = requests.post(
        "https://api.swarms.world/v1/agent/completions",
        headers={"x-api-key": "your-api-key"},
        json=payload
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const payload = {
        agent_config: {
            agent_name: "Problem Solver",
            description: "Agent that performs iterative problem-solving",
            system_prompt: "You are a problem-solving agent that breaks down complex tasks into steps and iteratively refines solutions.",
            model_name: "gpt-4.1",
            max_loops: 3,
            max_tokens: 4096,
            temperature: 0.7
        },
        task: "Solve this multi-step problem: First, research the current state of renewable energy. Then, identify the top 3 challenges. Finally, propose solutions for each challenge."
    };

    const response = await fetch('https://api.swarms.world/v1/agent/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-api-key': 'your-api-key'
        },
        body: JSON.stringify(payload)
    });

    const result = await response.json();
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use reqwest;
    use serde_json::json;

    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        let client = reqwest::Client::new();
        
        let payload = json!({
            "agent_config": {
                "agent_name": "Problem Solver",
                "description": "Agent that performs iterative problem-solving",
                "system_prompt": "You are a problem-solving agent that breaks down complex tasks into steps and iteratively refines solutions.",
                "model_name": "gpt-4.1",
                "max_loops": 3,
                "max_tokens": 4096,
                "temperature": 0.7
            },
            "task": "Solve this multi-step problem: First, research the current state of renewable energy. Then, identify the top 3 challenges. Finally, propose solutions for each challenge."
        });

        let response = client
            .post("https://api.swarms.world/v1/agent/completions")
            .header("x-api-key", "your-api-key")
            .json(&payload)
            .send()
            .await?;

        let result: serde_json::Value = response.json().await?;
        println!("{:?}", result);
        
        Ok(())
    }
    ```
  </Tab>
</Tabs>

### Agent with Marketplace Prompt

Use pre-built prompts from the Swarms marketplace by specifying the `marketplace_prompt_id`. When using a marketplace prompt, you don't need to provide `agent_name`, `description`, or `system_prompt` - the system will automatically retrieve and use the prompt configuration from the marketplace, including the agent's name, description, and system prompt.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    payload = {
        "agent_config": {
            "marketplace_prompt_id": "1191250b-9fb3-42e0-b0e9-25ec83260ab2",
            "model_name": "gpt-4.1-mini",
            "max_tokens": 8192
        },
        "task": "Your task here"
    }

    response = requests.post(
        "https://api.swarms.world/v1/agent/completions",
        headers={"x-api-key": "your-api-key"},
        json=payload
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const payload = {
        agent_config: {
            marketplace_prompt_id: "1191250b-9fb3-42e0-b0e9-25ec83260ab2",
            model_name: "gpt-4.1-mini",
            max_tokens: 8192
        },
        task: "Your task here"
    };

    const response = await fetch('https://api.swarms.world/v1/agent/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-api-key': 'your-api-key'
        },
        body: JSON.stringify(payload)
    });

    const result = await response.json();
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use reqwest;
    use serde_json::json;

    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        let client = reqwest::Client::new();
        
        let payload = json!({
            "agent_config": {
                "marketplace_prompt_id": "1191250b-9fb3-42e0-b0e9-25ec83260ab2",
                "model_name": "gpt-4.1-mini",
                "max_tokens": 8192
            },
            "task": "Your task here"
        });

        let response = client
            .post("https://api.swarms.world/v1/agent/completions")
            .header("x-api-key", "your-api-key")
            .json(&payload)
            .send()
            .await?;

        let result: serde_json::Value = response.json().await?;
        println!("{:?}", result);
        
        Ok(())
    }
    ```
  </Tab>
</Tabs>

**Note**: When `marketplace_prompt_id` is provided, the system automatically fetches the agent's name, description, and system prompt from the marketplace. You can find marketplace prompts using the [Query Prompts API](/docs/marketplace/prompts-api#query-prompts).

### Agent with Image Analysis

Enable vision capabilities by providing base64-encoded images to your agent. The agent can analyze single or multiple images and answer questions about visual content. Use the `img` parameter for a single image or `imgs` for multiple images.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import requests
    import base64

    # Encode an image from a file
    with open("path/to/image.jpg", "rb") as image_file:
        base64_image = base64.b64encode(image_file.read()).decode('utf-8')

    # Or encode from a URL
    # import requests as req
    # response = req.get("https://example.com/image.jpg")
    # base64_image = base64.b64encode(response.content).decode('utf-8')

    payload = {
        "agent_config": {
            "agent_name": "Image Analyzer",
            "description": "AI agent specialized in image analysis",
            "system_prompt": "You are an expert at analyzing and describing images in detail.",
            "model_name": "gpt-4.1",
            "max_tokens": 2048,
            "temperature": 0.5
        },
        "task": "Describe what you see in this image in detail",
        "img": base64_image
    }

    response = requests.post(
        "https://api.swarms.world/v1/agent/completions",
        headers={"x-api-key": "your-api-key"},
        json=payload
    )

    result = response.json()
    print(result['outputs'][0]['content'])
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import * as fs from 'fs';

    // Encode an image from a file
    const imageBuffer = fs.readFileSync('path/to/image.jpg');
    const base64Image = imageBuffer.toString('base64');

    // Or encode from a URL
    // const imageResponse = await fetch('https://example.com/image.jpg');
    // const arrayBuffer = await imageResponse.arrayBuffer();
    // const base64Image = Buffer.from(arrayBuffer).toString('base64');

    const payload = {
        agent_config: {
            agent_name: "Image Analyzer",
            description: "AI agent specialized in image analysis",
            system_prompt: "You are an expert at analyzing and describing images in detail.",
            model_name: "gpt-4.1",
            max_tokens: 2048,
            temperature: 0.5
        },
        task: "Describe what you see in this image in detail",
        img: base64Image
    };

    const response = await fetch('https://api.swarms.world/v1/agent/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-api-key': 'your-api-key'
        },
        body: JSON.stringify(payload)
    });

    const result = await response.json();
    console.log(result.outputs[0].content);
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use reqwest;
    use serde_json::json;
    use base64::{Engine as _, engine::general_purpose};
    use std::fs;

    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        let client = reqwest::Client::new();

        // Encode an image from a file
        let image_bytes = fs::read("path/to/image.jpg")?;
        let base64_image = general_purpose::STANDARD.encode(&image_bytes);

        let payload = json!({
            "agent_config": {
                "agent_name": "Image Analyzer",
                "description": "AI agent specialized in image analysis",
                "system_prompt": "You are an expert at analyzing and describing images in detail.",
                "model_name": "gpt-4.1",
                "max_tokens": 2048,
                "temperature": 0.5
            },
            "task": "Describe what you see in this image in detail",
            "img": base64_image
        });

        let response = client
            .post("https://api.swarms.world/v1/agent/completions")
            .header("x-api-key", "your-api-key")
            .json(&payload)
            .send()
            .await?;

        let result: serde_json::Value = response.json().await?;
        println!("{}", result["outputs"][0]["content"]);

        Ok(())
    }
    ```
  </Tab>
</Tabs>

**Supported Models**: Only vision-capable models support image analysis:

* `gpt-4.1`: Best for detailed visual analysis
* `gpt-4.1-mini`: Cost-effective for basic vision tasks
* `claude-sonnet-4-20250514`: High-quality vision understanding

**Image Processing**: The API automatically calculates image token costs based on resolution. Larger images consume more tokens. See the [Vision Capabilities](/docs/examples/examples/vision-capabilities) guide for detailed information on image encoding and best practices.

## Batch Processing

Process multiple agent completions simultaneously using the batch endpoint. This is useful for parallel processing of multiple tasks or running the same task with different configurations.

<Note>
  **Premium Tier Required**: The `/v1/agent/batch/completions` endpoint is available only on Pro, Ultra, and Premium plans. [Upgrade your account](https://swarms.world/platform/account) to access batch processing capabilities.
</Note>

For processing multiple agents simultaneously, use the batch endpoint:

**Endpoint**: `/v1/agent/batch/completions`

**Request**: Array of `AgentCompletion` objects (max 50 per batch)

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    payloads = [
        {
            "agent_config": {
                "agent_name": "Analyst 1",
                "system_prompt": "You are a financial analyst.",
                "model_name": "gpt-4.1-mini"
            },
            "task": "Analyze Q1 financial results"
        },
        {
            "agent_config": {
                "agent_name": "Analyst 2", 
                "system_prompt": "You are a market analyst.",
                "model_name": "gpt-4.1-mini"
            },
            "task": "Evaluate market trends"
        }
    ]

    response = requests.post(
        "https://api.swarms.world/v1/agent/batch/completions",
        headers={"x-api-key": "your-api-key"},
        json=payloads
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const payloads = [
        {
            agent_config: {
                agent_name: "Analyst 1",
                system_prompt: "You are a financial analyst.",
                model_name: "gpt-4.1-mini"
            },
            task: "Analyze Q1 financial results"
        },
        {
            agent_config: {
                agent_name: "Analyst 2",
                system_prompt: "You are a market analyst.",
                model_name: "gpt-4.1-mini"
            },
            task: "Evaluate market trends"
        }
    ];

    const response = await fetch('https://api.swarms.world/v1/agent/batch/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-api-key': 'your-api-key'
        },
        body: JSON.stringify(payloads)
    });

    const result = await response.json();
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use reqwest;
    use serde_json::json;

    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        let client = reqwest::Client::new();
        
        let payloads = json!([
            {
                "agent_config": {
                    "agent_name": "Analyst 1",
                    "system_prompt": "You are a financial analyst.",
                    "model_name": "gpt-4.1-mini"
                },
                "task": "Analyze Q1 financial results"
            },
            {
                "agent_config": {
                    "agent_name": "Analyst 2",
                    "system_prompt": "You are a market analyst.",
                    "model_name": "gpt-4.1-mini"
                },
                "task": "Evaluate market trends"
            }
        ]);

        let response = client
            .post("https://api.swarms.world/v1/agent/batch/completions")
            .header("x-api-key", "your-api-key")
            .json(&payloads)
            .send()
            .await?;

        let result: serde_json::Value = response.json().await?;
        println!("{:?}", result);
        
        Ok(())
    }
    ```
  </Tab>
</Tabs>

## Error Handling

The API returns appropriate HTTP status codes and error messages:

* **400 Bad Request**: Invalid input parameters or validation failures
* **401 Unauthorized**: Missing or invalid API key
* **422 Unprocessable Entity**: Schema validation failures (e.g. a non-positive `max_loops` or `max_tokens`)
* **429 Too Many Requests**: Rate limit exceeded
* **500 Internal Server Error**: Server-side processing errors

If an agent run produces no output for the given task, the API returns **HTTP 400** with a detail message like `Agent '<name>' produced no output for this task. Nothing was charged...` instead of a success response. Callers should treat this as a retryable, client-visible error — nothing is billed for it.

## Rate Limits

Rate limits are tier-based:

* **Free Tier**: 100 requests/minute, 350 requests/hour, 1,200 requests/day
* **Premium Tier**: 2,000 requests/minute, 10,000 requests/hour, 100,000 requests/day

## Cost Calculation

For detailed pricing information, see the <a href="/docs/documentation/resources/pricing">Pricing</a> page.

## Best Practices

1. **Agent Naming**: Use descriptive, unique names for agents
2. **System Prompts**: Provide clear, specific instructions for consistent behavior
3. **Temperature Settings**: Use lower values (0.1-0.3) for analytical tasks, higher values (0.7-0.9) for creative tasks
4. **Token Limits**: Set appropriate max\_tokens based on expected response length
5. **History Management**: Keep conversation history concise to manage token costs
6. **Error Handling**: Implement proper error handling for production applications
7. **Rate Limiting**: Monitor usage and implement backoff strategies for rate limit handling

## Integration Examples

### Python SDK Usage

Use the official Python SDK for a more convenient way to interact with the Swarms API. The SDK handles authentication, request formatting, and response parsing automatically.

* pip3 install -U swarms-client
* Put your `SWARMS_API_KEY`

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

load_dotenv()

client = SwarmsClient(
    api_key=os.getenv("SWARMS_API_KEY"),
)


result = client.agent.run(
    agent_config={
        "agent_name": "Bloodwork Diagnosis Expert",
        "description": "An expert doctor specializing in interpreting and diagnosing blood work results.",
        "system_prompt": (
            "You are an expert medical doctor specializing in the interpretation and diagnosis of blood work. "
            "Your expertise includes analyzing laboratory results, identifying abnormal values, "
            "explaining their clinical significance, and recommending next diagnostic or treatment steps. "
            "Provide clear, evidence-based explanations and consider differential diagnoses based on blood test findings."
        ),
        "model_name": "gpt-4.1",
        "max_loops": 1,
        "max_tokens": 1000,
        "temperature": 0.5,
    },
    task=(
        "A patient presents with the following blood work results: "
        "Hemoglobin: 10.2 g/dL (low), WBC: 13,000 /µL (high), Platelets: 180,000 /µL (normal), "
        "ALT: 65 U/L (high), AST: 70 U/L (high). "
        "Please provide a detailed interpretation, possible diagnoses, and recommended next steps."
    ),
)

print(json.dumps(result, indent=4))
```

### JavaScript/Node.js Integration

Integrate the Swarms API into your JavaScript or Node.js applications using native `fetch` or any HTTP client library. This example demonstrates a basic implementation using the Fetch API.

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    const response = await fetch('https://api.swarms.world/v1/agent/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-api-key': 'your-api-key'
        },
        body: JSON.stringify({
            agent_config: {
                agent_name: "TypeScript Agent",
                system_prompt: "You are a helpful assistant.",
                model_name: "gpt-4.1-mini"
            },
            task: "Explain TypeScript promises"
        })
    });

    const result = await response.json();
    ```
  </Tab>

  <Tab title="Rust">
    ```rust theme={null}
    use reqwest;
    use serde_json::json;

    #[tokio::main]
    async fn main() -> Result<(), Box<dyn std::error::Error>> {
        let client = reqwest::Client::new();
        
        let payload = json!({
            "agent_config": {
                "agent_name": "Rust Agent",
                "system_prompt": "You are a helpful assistant.",
                "model_name": "gpt-4.1-mini"
            },
            "task": "Explain Rust async/await"
        });

        let response = client
            .post("https://api.swarms.world/v1/agent/completions")
            .header("x-api-key", "your-api-key")
            .json(&payload)
            .send()
            .await?;

        let result: serde_json::Value = response.json().await?;
        println!("{:?}", result);
        
        Ok(())
    }
    ```
  </Tab>
</Tabs>

## Support and Resources

* **API Keys**: [https://swarms.world/platform/api-keys](https://swarms.world/platform/api-keys)
* **Technical Support**: [https://cal.com/swarms/swarms-technical-support](https://cal.com/swarms/swarms-technical-support)
* **Community**: [Discord](https://discord.gg/EamjgSaEQf)

## Further Examples

For end‑to‑end, copy‑pasteable examples built on top of this endpoint:

* **Single Agent Completion (REST)** – minimal `requests` example using the new `agent_config` format:\
  `/docs/examples/api_examples/agent_completion_single_agent`
* **Autonomous Agents with `max_loops="auto"`** – tutorial for fully autonomous, tool‑using agents:\
  `/docs/examples/api_examples/autonomous_agent_tutorial`


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