> ## 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). Only one tool is attached per request: if both are listed, `auto_search` takes precedence and `web_scraper` is ignored. 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       | `"gpt-4.1"`    | 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                                                                                                                                                                                                                                                                                               |
| `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       | `8192`         | The maximum number of tokens that the agent is allowed to generate in its responses, limiting output length                                                                                                                                                                                                                                                                                                                                  |
| `temperature`                 | `float`                  | 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 (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`                   | `Union[int, string]`     | No       | `1`            | Maximum number of iterations the agent can perform for its task. Accepts an integer for a fixed count, or 'auto' to allow the system to determine the necessary number based on the task's complexity                                                                                                                                                                                                                                        |
| `tools_list_dictionary`       | `List[Dict]`             | No       | -              | A dictionary of tools that the agent can use to complete its task                                                                                                                                                                                                                                                                                                                                                                            |
| `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`. 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                                                                                                                                                                                                                                                                                                                                                                        |
| `streaming_on`                | `boolean`                | No       | `false`        | A flag indicating whether the agent should stream its output                                                                                                                                                                                                                                                                                                                                                                                 |
| `llm_args`                    | `Dict`                   | No       | -              | Additional arguments to pass to the LLM such as top\_p, frequency\_penalty, presence\_penalty, etc.                                                                                                                                                                                                                                                                                                                                          |
| `dynamic_temperature_enabled` | `boolean`                | No       | `true`         | A flag indicating whether the agent should dynamically adjust its temperature based on the task                                                                                                                                                                                                                                                                                                                                              |
| `mcp_config`                  | `MCPConnection`          | No       | -              | The MCP connection to use for the agent                                                                                                                                                                                                                                                                                                                                                                                                      |
| `mcp_configs`                 | `MultipleMCPConnections` | No       | -              | The MCP connections to use for the agent. This is a list of MCP connections. Includes multiple MCP connections                                                                                                                                                                                                                                                                                                                               |
| `tool_call_summary`           | `boolean`                | No       | `true`         | A parameter enabling an agent to summarize tool calls                                                                                                                                                                                                                                                                                                                                                                                        |
| `reasoning_effort`            | `string`                 | No       | `"low"`        | The effort to put into reasoning. Options: `low`, `medium`, `high`                                                                                                                                                                                                                                                                                                                                                                           |
| `thinking_tokens`             | `integer`                | No       | -              | The number of tokens to use for thinking                                                                                                                                                                                                                                                                                                                                                                                                     |
| `reasoning_enabled`           | `boolean`                | No       | `false`        | A parameter enabling an agent to use reasoning                                                                                                                                                                                                                                                                                                                                                                                               |
| `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                                                                                                                                                                                                                                                                                              |

## 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.0056
  }
}
```

## 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. Note that only one of these tools can be active per request: if both are listed, `auto_search` takes precedence and `web_scraper` is ignored.

<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 MCP server for additional tools and resources.

<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 10 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
* **429 Too Many Requests**: Rate limit exceeded
* **500 Internal Server Error**: Server-side processing errors

## Rate Limits

Rate limits are tier-based:

* **Free Tier**: 100 requests/minute, 350 requests/hour, 50\*24 requests/day
* **Premium Tier**: 2000 requests/minute, 10000 requests/hour, 100000 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`
