Skip to main content
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

AgentSpec Object

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:
Every server must be a publicly reachable https:// URL. An http:// URL, a stdio server (transport: "stdio" or a command), or an entry with no URL returns 422 MCP servers must be https:// URLs; stdio servers are not accepted. For anything that needs authentication, a custom transport, or non-default timeouts, pass an MCPConnection object instead.

MCPConnection Object

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.
Send credentials as literal values. A string anywhere in an MCP entry that starts with env: or ${ (an environment variable reference such as "env:MY_VAR" or "${MY_VAR}") returns 422 MCP credentials must be sent as values; env:NAME and ${NAME} references are not accepted, because it would be read from the API server’s environment, not yours:
Client-credentials OAuth example:
MCP servers add no fee. Attaching servers through mcp_url, mcp_urls, mcp_config, or mcp_configs is free; the request is billed only for the agent’s tokens at its model’s price (see the Pricing page).

Response Schema

AgentCompletionOutput Object

Usage Information

The response includes detailed usage metrics. For example, a claude-sonnet-5 agent sent one image:
image_count is the number of images in the request, counted across img and imgs, and img_cost is $0.02 per image. total_cost is the token cost, priced at the agent’s own model plus the 15% service fee, plus img_cost, plus the flat auto_search fee when auto_search is in tools_enabled. The token counts and cost include any handoffs agents, each priced at its own model. flash_sale_applied is true only when a flash sale discount priced the tokens. See the Pricing page for per-model prices and flat fees.

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, the stream instead emits a single event: error frame and closes without usage, end or done events. Because the HTTP status is sent when the stream opens, these errors arrive inside a 200 response:
  • The model provider rejected or failed the call (see Provider errors): the frame carries the status code the non-streaming request would have returned, and nothing is charged.
  • Any other failure, including request validation that runs after the stream opens (an unknown model, a premium model on a free-tier key, a missing task): data: {"error": "AgentCompletionError: <status>: <detail>", "timestamp": "..."}.
Check for an error event rather than relying on the HTTP status when streaming.

Features and Capabilities

1. Multi-Model Support

  • OpenAI Models: gpt-4.1, gpt-4.1-mini, gpt-4o
  • Anthropic Models: claude-sonnet-5, claude-opus-5
  • 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
  • Flat per-image fee across img and imgs; image input tokens are billed at the model’s price

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.

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.

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. Only auto_search adds a flat fee (once per request); web_scraper is free apart from the tokens the agent uses.

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. The server must be reachable at a public https:// URL. For authenticated servers, multiple servers, and OAuth, see MCP Connections.

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.

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.
The agent’s outputs content contains the structured tool call. The function.arguments field arrives as a JSON string, so parse it before use:
For schema-enforced plain-JSON responses without tool calls, you can alternatively pass response_format inside llm_args. See Structured Outputs for a comparison of both approaches.

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.

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

Agent with Image Analysis

Enable vision capabilities by providing images to your agent as base64 data, data:image/... URIs, or https:// URLs. 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.
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-5: High-quality vision understanding
Image Billing: Each image in img or imgs is billed a flat $0.02, and the input tokens the model provider reports for the request, images included, are billed at the model’s own price. See the 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.
Premium Tier Required: The /v1/agent/batch/completions endpoint is available only on Pro, Ultra, and Premium plans. Upgrade your account to access batch processing capabilities.
For processing multiple agents simultaneously, use the batch endpoint: Endpoint: /v1/agent/batch/completions Request: Array of AgentCompletion objects (max 50 per batch)
Response: the batch returns 200 with one entry in results per request, in request order, even when some of them fail. A successful entry is a normal AgentCompletionOutput; a failed entry carries the error the single-agent endpoint would have returned, and is not charged:
A batch of more than 50 requests returns 422, and a free-tier key gets 403 premium_access_required.

Error Handling

The API returns appropriate HTTP status codes and error messages:
  • 400 Bad Request: Invalid input parameters or validation failures, including a missing or blank task with no history
  • 401 Unauthorized: Missing or invalid API key
  • 402 Payment Required: insufficient_credits, when the account’s purchased credit balance is $1.00 or less
  • 403 Forbidden: Premium model access required, when a free-tier key requests a premium-only model (in model_name, fallback_models, fallback_model_name or any handoffs agent)
  • 404 Not Found: The model does not exist or is no longer available: The model '<name>' does not exist or is no longer available. See https://api.swarms.world/v1/models/available for the models you can use.
  • 422 Unprocessable Entity: Schema validation failures, for example a non-positive max_loops or max_tokens, a blocked or unknown selected_tools name, an llm_args key outside the accepted list, a non-https:// or stdio MCP server, an env:/${...} MCP credential, or an image that is not base64, a data:image URI or an https:// URL
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server-side processing errors
  • 503 Service Unavailable: Unable to verify your subscription status. Retry in a few seconds., when a premium-only model is requested and the subscription lookup fails. Retry; it is not a tier answer
The 4xx and 503 errors above are returned before the agent runs, so nothing is charged. A 422 from schema validation has this shape:

Provider errors

When the model provider fails the call, the API returns the provider’s reason instead of an empty result. Nothing is charged: The 429 and 502 are safe to retry. If a run returns no output and the provider reported no error, 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.

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. Every paid plan (pro, ultra, premium, or an active subscription) gets these same limits.
The limits count logged completions, not HTTP requests: a completion that finishes counts once, while GET requests and failed requests don’t count. A batch of N agent completions counts N + 1 (one per item that completes, plus one for the batch). The windows span every API key on your account. Check your current counts with GET /v1/rate/limits.

Cost Calculation

For detailed pricing information, see the Pricing 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

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.

Support and Resources

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