/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-keyheader;Authorization: Bearer <key>is also accepted) - Rate Limiting: Subject to tier-based rate limits
Request Schema
AgentCompletion Object
AgentSpec Object
MCP Connections
FourAgentSpec 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:
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
Setoauth on an MCPConnection to authenticate against a server that requires OAuth 2.1. Three flavors are supported, selected by which fields you set:
grant_type: "authorization_code"(default) — the interactive browser flow from the MCP authorization spec. PKCE and RFC 7591 dynamic client registration are handled automatically, soclient_idis optional. Tokens are cached on disk so the browser prompt only happens once.grant_type: "client_credentials"— a headless machine-to-machine flow. Requiresclient_id/client_secret. The token endpoint is discovered from the server’s/.well-known/oauth-authorization-servermetadata unlesstoken_urlis given.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:
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, aclaude-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
Setagent_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:
- An initial
data:frame with noevent:line, carrying job metadata:job_id,success,name,description,temperature,timestamp,stream: true,type: "metadata". event: start—data: {"message": "Starting agent processing..."}event: chunk— one per generated token,data: {"content": "<token>", "timestamp": "..."}. Repeats until the agent finishes.event: usage—data:the same usage object described above.event: end—data: {"job_id": ..., "usage": {...}, "timestamp": ..., "complete": true}event: done—data: {"message": "Agent processing complete"}
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": "..."}.
error event rather than relying on the HTTP status when streaming.
- Python
- TypeScript
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
imgparameter - Multiple image analysis via
imgsparameter - Flat per-image fee across
imgandimgs; 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_enabledparameter (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.- Python
- TypeScript
- Rust
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.- Python
- TypeScript
- Rust
Agent with Search Capabilities
Enable web search functionality for your agent by includingauto_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.
- Python
- TypeScript
- Rust
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 publichttps:// URL. For authenticated servers, multiple servers, and OAuth, see MCP Connections.
- Python
- TypeScript
- Rust
Agent with Custom LLM Arguments
Customize advanced LLM parameters such astop_p, frequency_penalty, and presence_penalty to fine-tune the model’s behavior. This is useful for controlling creativity, repetition, and topic diversity.
- Python
- TypeScript
- Rust
Agent with Structured Outputs
Usetools_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.
- Python
- TypeScript
- Rust
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 themax_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.
- Python
- TypeScript
- Rust
Agent with Marketplace Prompt
Use pre-built prompts from the Swarms marketplace by specifying themarketplace_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.
- Python
- TypeScript
- Rust
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.
- Python
- TypeScript
- Rust
gpt-4.1: Best for detailed visual analysisgpt-4.1-mini: Cost-effective for basic vision tasksclaude-sonnet-5: High-quality vision understanding
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./v1/agent/batch/completions
Request: Array of AgentCompletion objects (max 50 per batch)
- Python
- TypeScript
- Rust
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:
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
taskwith nohistory - 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 (inmodel_name,fallback_models,fallback_model_nameor anyhandoffsagent) - 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_loopsormax_tokens, a blocked or unknownselected_toolsname, anllm_argskey outside the accepted list, a non-https://orstdioMCP server, anenv:/${...}MCP credential, or an image that is not base64, adata:imageURI or anhttps://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
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.
GET /v1/rate/limits.
Cost Calculation
For detailed pricing information, see the Pricing page.Best Practices
- Agent Naming: Use descriptive, unique names for agents
- System Prompts: Provide clear, specific instructions for consistent behavior
- Temperature Settings: Use lower values (0.1-0.3) for analytical tasks, higher values (0.7-0.9) for creative tasks
- Token Limits: Set appropriate max_tokens based on expected response length
- History Management: Keep conversation history concise to manage token costs
- Error Handling: Implement proper error handling for production applications
- 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 nativefetch or any HTTP client library. This example demonstrates a basic implementation using the Fetch API.
- TypeScript
- Rust
Support and Resources
- API Keys: https://swarms.world/platform/api-keys
- Technical Support: https://cal.com/swarms/swarms-technical-support
- Community: Discord
Further Examples
For end‑to‑end, copy‑pasteable examples built on top of this endpoint:- Single Agent Completion (REST) – minimal
requestsexample using the newagent_configformat:
/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