/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:
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.
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:
Every
AgentCompletion request that sets agent_config.mcp_url is charged the MCP call fee (see the 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.Response Schema
AgentCompletionOutput Object
Usage Information
The response includes detailed usage metrics: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). See the Pricing page for the underlying per-token and per-call rates.
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 — data: {"error": "AgentCompletionError: ...", "timestamp": "..."} — and closes without a done event.
- Python
- TypeScript
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
imgparameter - Multiple image analysis via
imgsparameter - 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_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 and each is billed its own flat fee.
- 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. 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 base64-encoded images to your agent. The agent can analyze single or multiple images and answer questions about visual content. Use theimg 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-4-20250514: High-quality vision understanding
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
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_loopsormax_tokens) - 429 Too Many Requests: Rate limit exceeded
- 500 Internal Server Error: Server-side processing errors
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 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