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

# Available Models

> Discover and explore all available AI models supported by the Swarms API

Get a comprehensive list of all AI models available through the Swarms API. This endpoint provides information about supported models from various providers including OpenAI, Anthropic, Groq, and others.

> [!NOTE]
>
> The `/v1/models/available` endpoint returns all models currently supported by the Swarms API, each with its price per 1M input and output tokens (15% service fee included).

## Quick Start

> [tab] Python
>
> ```python theme={null}
> import requests
> import json
> import os
> from dotenv import load_dotenv
>
> load_dotenv()
>
> API_KEY = os.getenv("SWARMS_API_KEY")
> BASE_URL = "https://api.swarms.world"
>
> headers = {
>     "x-api-key": API_KEY,
>     "Content-Type": "application/json"
> }
>
> def get_available_models():
>     """Get all available models"""
>     response = requests.get(
>         f"{BASE_URL}/v1/models/available",
>         headers=headers
>     )
>
>     if response.status_code == 200:
>         return response.json()
>     else:
>         print(f"Error: {response.status_code} - {response.text}")
>         return None
>
> # Get available models
> models_data = get_available_models()
> if models_data:
>     print("✅ Available models retrieved successfully!")
>     print(f"Model count: {models_data['count']}")
>     for model in models_data["models"][:5]:
>         print(
>             f"{model['model_name']}: ${model['input_cost_per_1m']} input, "
>             f"${model['output_cost_per_1m']} output per 1M tokens"
>         )
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> const API_KEY = process.env.SWARMS_API_KEY;
> const BASE_URL = "https://api.swarms.world";
>
> const headers = {
>     "x-api-key": API_KEY,
>     "Content-Type": "application/json"
> };
>
> async function getAvailableModels() {
>     try {
>         const response = await fetch(`${BASE_URL}/v1/models/available`, {
>             method: 'GET',
>             headers: headers
>         });
>
>         if (!response.ok) {
>             throw new Error(`HTTP error! status: ${response.status}`);
>         }
>
>         const data = await response.json();
>         console.log("✅ Available models retrieved successfully!");
>         console.log(JSON.stringify(data, null, 2));
>         return data;
>     } catch (error) {
>         console.error('Error:', error);
>         return null;
>     }
> }
>
> // Get available models
> getAvailableModels();
> ```

> [tab] cURL
>
> ```bash theme={null}
> # Get available models
> curl -X GET "https://api.swarms.world/v1/models/available" \
>   -H "x-api-key: your-api-key" \
>   -H "Content-Type: application/json"
>
> # Example response (truncated):
> # {
> #   "success": true,
> #   "count": 1894,
> #   "models": [
> #     {"model_name": "gpt-5.4", "input_cost_per_1m": 2.875, "output_cost_per_1m": 17.25, "price_source": "litellm"},
> #     {"model_name": "claude-sonnet-5", "input_cost_per_1m": 2.3, "output_cost_per_1m": 11.5, "price_source": "litellm"},
> #     {"model_name": "openrouter/moonshotai/kimi-k3", "input_cost_per_1m": 0.8395, "output_cost_per_1m": 11.5, "price_source": "openrouter"}
> #   ]
> # }
> ```

## Understanding the Response

The models endpoint returns every model available to your subscription tier, each with its price per 1M tokens. Prices below are examples at the time of writing (truncated to a few models); call the endpoint for current prices:

```json theme={null}
{
  "success": true,
  "count": 1894,
  "models": [
    {
      "model_name": "gpt-5.4",
      "input_cost_per_1m": 2.875,
      "output_cost_per_1m": 17.25,
      "price_source": "litellm"
    },
    {
      "model_name": "gpt-4.1",
      "input_cost_per_1m": 2.3,
      "output_cost_per_1m": 9.2,
      "price_source": "litellm"
    },
    {
      "model_name": "claude-sonnet-5",
      "input_cost_per_1m": 2.3,
      "output_cost_per_1m": 11.5,
      "price_source": "litellm"
    },
    {
      "model_name": "claude-haiku-4-5",
      "input_cost_per_1m": 1.15,
      "output_cost_per_1m": 5.75,
      "price_source": "litellm"
    },
    {
      "model_name": "openrouter/moonshotai/kimi-k3",
      "input_cost_per_1m": 0.8395,
      "output_cost_per_1m": 11.5,
      "price_source": "openrouter"
    }
  ]
}
```

| Field | Type | Description |
| - | - | - |
| `success` | boolean | Whether the request succeeded |
| `count` | integer | Number of models in the `models` list |
| `models` | array of objects | Every available model with its price, filtered by your subscription tier (free tier accounts won't see [premium-only](https://docs.swarms.ai/docs/documentation/resources/pricing.md#premium-only-models) or Groq models) |

Each entry in `models` has these fields:

| Field | Type | Description |
| - | - | - |
| `model_name` | string | The model identifier to pass as `model_name` |
| `input_cost_per_1m` | number | Price per 1M input tokens (USD), including the 15% service fee |
| `output_cost_per_1m` | number | Price per 1M output tokens (USD), including the 15% service fee |
| `price_source` | string | Where the price came from: `openrouter` for `openrouter/...` models, `litellm` for the rest, or `fallback` when there is no price data for the model. OpenRouter free models (ids ending in `:free`, and `openrouter/openrouter/free`) are \$0 with `price_source` `openrouter` |

> [!WARNING]
>
> `models` used to be a list of strings. It is now a list of objects, so read each name from `model_name`: use `[m["model_name"] for m in data["models"]]` instead of `data["models"]`, and `"gpt-5.4" in {m["model_name"] for m in data["models"]}` for membership checks.

By default, this list also includes models fetched live from OpenRouter (cached for 5 minutes) and prefixed with `openrouter/` (e.g. `openrouter/aion-labs/aion-3.0`). The base catalog is precomputed and cached server-side, so this endpoint is cheap to call.

## Pricing for One Model

To look up a single model's price, call `GET /v1/models/pricing` with the model name as the `model_name` query parameter. Any model name gets a price, listed or not:

> [tab] Python
>
> ```python theme={null}
> response = requests.get(
>     f"{BASE_URL}/v1/models/pricing",
>     headers=headers,
>     params={"model_name": "gpt-5.4"},
> )
> price = response.json()
> print(
>     f"{price['model_name']}: ${price['input_cost_per_1m']} input, "
>     f"${price['output_cost_per_1m']} output per 1M tokens ({price['price_source']})"
> )
> ```

> [tab] cURL
>
> ```bash theme={null}
> curl -G "https://api.swarms.world/v1/models/pricing" \
>   --data-urlencode "model_name=gpt-5.4" \
>   -H "x-api-key: $SWARMS_API_KEY"
> ```

Example response (prices at the time of writing, 15% service fee included):

```json theme={null}
{
  "status": "success",
  "model_name": "gpt-5.4",
  "input_cost_per_1m": 2.875,
  "output_cost_per_1m": 17.25,
  "price_source": "litellm",
  "timestamp": "2026-10-12T19:01:46.491705+00:00"
}
```

`price_source: "fallback"` means there is no price data for that model name. A run on it is billed at the fallback rates of \$6.50 per 1M input and \$18.50 per 1M output tokens before the fee, so the endpoint returns \$7.475 and \$21.275 for it. See [Pricing](https://docs.swarms.ai/docs/documentation/resources/pricing.md) for how token costs and flat fees add up.

## OpenAI-Compatible Model List

If you use the OpenAI SDK (or any client that discovers models via `GET /v1/models`), the same tier-filtered catalog is available in the standard OpenAI list format:

> [tab] Python
>
> ```python theme={null}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key=API_KEY,
>     base_url="https://api.swarms.world/v1",
> )
>
> models = client.models.list()
> print(f"{len(models.data)} models available")
> for model in models.data[:10]:
>     print(f"{model.id} (owned_by: {model.owned_by})")
> ```

> [tab] cURL
>
> ```bash theme={null}
> curl -X GET "https://api.swarms.world/v1/models" \
>   -H "x-api-key: your-api-key"
>
> # Example response:
> # {
> #   "object": "list",
> #   "data": [
> #     {"id": "gpt-5.4", "object": "model", "created": 0, "owned_by": "openai",
> #      "pricing": {"input_cost_per_1m": 2.875, "output_cost_per_1m": 17.25, "price_source": "litellm"}}
> #   ]
> # }
> ```

Each entry has `id` (the model identifier you pass as `model_name` or `model`), `object` (always `"model"`), `created`, `owned_by` (the resolved provider, e.g. `openai`, `anthropic`), and `pricing` (`input_cost_per_1m`, `output_cost_per_1m` and `price_source`, the same values `/v1/models/available` returns). See the [OpenAI-Compatible Endpoint](https://docs.swarms.ai/docs/documentation/capabilities/openai-compatible.md) reference for using these models with the OpenAI SDK.

## Model Selection Guide

### For Text Generation

> [tab] Creative Tasks
>
> ```python theme={null}
> # Best for creative writing, brainstorming, content generation
> recommended_models = [
>     "gpt-4.1",                    # Most capable, balanced performance
>     "claude-sonnet-5", # Excellent for creative tasks
>     "gpt-4.1-mini"               # Fast and cost-effective
> ]
> ```

> [tab] Analytical Tasks
>
> ```python theme={null}
> # Best for analysis, reasoning, complex problem-solving
> recommended_models = [
>     "gpt-4.1",                    # Superior reasoning capabilities
>     "claude-sonnet-5", # Strong analytical performance
>     "gpt-4-turbo"               # Good balance of speed and capability
> ]
> ```

> [tab] Fast Responses
>
> ```python theme={null}
> # Best for quick responses, simple tasks, cost optimization
> recommended_models = [
>     "gpt-4.1-mini",              # Fastest and most cost-effective
>     "groq/openai/gpt-oss-20b",     # Very fast inference
>     "claude-haiku-4-5"         # Fast with good quality
> ]
> ```

## Model Capabilities

> [tab] Vision Models
>
> ```python theme={null}
> # Models that support image analysis
> vision_models = [
>     "gpt-4.1",           # Best vision capabilities
>     "gpt-4-turbo",      # Good vision support
>     "gpt-4.1-mini"      # Basic vision support
> ]
>
> # Example: Vision-enabled agent
> payload = {
>     "agent_config": {
>         "agent_name": "Vision Analyst",
>         "model_name": "gpt-4.1",  # Vision-capable model
>         "max_tokens": 2048
>     },
>     "task": "Describe this image in detail",
>     "img": "https://example.com/image.jpg"
> }
> ```

> [tab] Streaming Models
>
> ```python theme={null}
> # Models that support streaming responses
> streaming_models = [
>     "gpt-4.1",
>     "gpt-4.1-mini",
>     "claude-sonnet-5",
>     "claude-haiku-4-5"
> ]
>
> # Example: Streaming-enabled agent
> payload = {
>     "agent_config": {
>         "agent_name": "Streaming Writer",
>         "model_name": "gpt-4.1",
>         "streaming_on": True,  # Enable streaming
>         "max_tokens": 2048
>     },
>     "task": "Write a creative story"
> }
> ```

> [tab] Large Context Models
>
> ```python theme={null}
> # Models with large context windows
> large_context_models = [
>     "gpt-4.1",                    # 128k+ tokens
>     "claude-sonnet-5", # 200k+ tokens
>     "gpt-4-turbo",             # 128k tokens
> ]
>
> # Example: Large document analysis
> payload = {
>     "agent_config": {
>         "agent_name": "Document Analyst",
>         "model_name": "gpt-4.1",  # Large context
>         "max_tokens": 4096
>     },
>     "task": "Analyze this 50-page document and provide insights"
> }
> ```

## Dynamic Model Selection

> [tab] Python
>
> ```python theme={null}
> def select_best_model(task_type, priority="balanced"):
>     """
>     Dynamically select the best model based on task type and priority
>
>     Args:
>         task_type: Type of task ("creative", "analytical", "fast", "vision")
>         priority: Priority ("quality", "speed", "cost", "balanced")
>     """
>     # Get available models first
>     models_data = get_available_models()
>     if not models_data or not models_data.get("success"):
>         return "gpt-4.1-mini"  # Fallback
>
>     available_models = {m["model_name"] for m in models_data.get("models", [])}
>
>     # Model selection logic
>     if task_type == "creative":
>         if priority == "quality":
>             return "gpt-4.1" if "gpt-4.1" in available_models else "claude-sonnet-5"
>         elif priority == "speed":
>             return "gpt-4.1-mini" if "gpt-4.1-mini" in available_models else "claude-haiku-4-5"
>         else:  # balanced
>             return "gpt-4.1-mini"
>
>     elif task_type == "analytical":
>         return "gpt-4.1" if "gpt-4.1" in available_models else "claude-sonnet-5"
>
>     elif task_type == "fast":
>         return "gpt-4.1-mini" if "gpt-4.1-mini" in available_models else "groq/openai/gpt-oss-20b"
>
>     elif task_type == "vision":
>         return "gpt-4.1" if "gpt-4.1" in available_models else "gpt-4-turbo"
>
>     return "gpt-4.1-mini"  # Default fallback
>
> # Example usage
> best_model = select_best_model("creative", "quality")
> print(f"Selected model: {best_model}")
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> function selectBestModel(taskType, priority = "balanced") {
>     // Model selection logic for JavaScript
>     const modelPreferences = {
>         creative: {
>             quality: ["gpt-4.1", "claude-sonnet-5"],
>             speed: ["gpt-4.1-mini", "claude-haiku-4-5"],
>             balanced: ["gpt-4.1-mini"],
>             cost: ["gpt-4.1-mini", "groq/openai/gpt-oss-20b"]
>         },
>         analytical: {
>             quality: ["gpt-4.1", "claude-sonnet-5"],
>             speed: ["gpt-4-turbo"],
>             balanced: ["gpt-4.1"],
>             cost: ["gpt-4.1-mini"]
>         },
>         fast: {
>             quality: ["gpt-4.1-mini"],
>             speed: ["gpt-4.1-mini", "groq/openai/gpt-oss-20b"],
>             balanced: ["gpt-4.1-mini"],
>             cost: ["gpt-4.1-mini", "groq/openai/gpt-oss-20b"]
>         },
>         vision: {
>             quality: ["gpt-4.1"],
>             speed: ["gpt-4.1-mini"],
>             balanced: ["gpt-4.1"],
>             cost: ["gpt-4-turbo"]
>         }
>     };
>
>     const candidates = modelPreferences[taskType]?.[priority] || ["gpt-4.1-mini"];
>     return candidates[0]; // Return first preference
> }
>
> // Example usage
> const bestModel = selectBestModel("creative", "quality");
> console.log(`Selected model: ${bestModel}`);
> ```

## Model Performance Comparison

> [!NOTE]
>
> Every `groq/*` model is premium-only: a free-tier key gets 403 for the `groq/...` ids on this page. See [Premium-Only Models](https://docs.swarms.ai/docs/documentation/resources/pricing.md#premium-only-models).

| Model | Context Window | Best For | Speed | Cost |
| - | - | - | - | - |
| `gpt-4.1` | 128k+ | Complex reasoning, vision | Medium | High |
| `gpt-4.1-mini` | 128k+ | General purpose, fast tasks | Fast | Low |
| `claude-sonnet-5` | 200k+ | Creative writing, analysis | Medium | High |
| `claude-haiku-4-5` | 200k+ | Fast responses | Fast | Low |
| `groq/openai/gpt-oss-120b` | 128k | Complex tasks | Medium | Medium |
| `groq/openai/gpt-oss-20b` | 128k | Simple tasks | Fast | Low |

## Cost Optimization

Each model has its own price. To compare real costs, read `input_cost_per_1m` and `output_cost_per_1m` from `/v1/models/available` (or `/v1/models/pricing`) rather than relying on the rough tiers below.

> [tab] Python
>
> ```python theme={null}
> def optimize_model_selection(task_complexity, budget_constraint):
>     """
>     Select optimal model based on task complexity and budget
>     """
>     if task_complexity == "low":
>         return "gpt-4.1-mini" if budget_constraint == "strict" else "groq/openai/gpt-oss-20b"
>     elif task_complexity == "medium":
>         return "gpt-4.1-mini" if budget_constraint == "strict" else "gpt-4.1"
>     else:  # high complexity
>         return "claude-sonnet-5" if budget_constraint == "flexible" else "gpt-4.1"
>
> # Example usage
> model = optimize_model_selection("high", "flexible")
> print(f"Optimized model: {model}")
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> function optimizeModelSelection(taskComplexity, budgetConstraint) {
>     const optimizationMatrix = {
>         low: {
>             strict: "gpt-4.1-mini",
>             flexible: "groq/openai/gpt-oss-20b"
>         },
>         medium: {
>             strict: "gpt-4.1-mini",
>             flexible: "gpt-4.1"
>         },
>         high: {
>             strict: "gpt-4.1",
>             flexible: "claude-sonnet-5"
>         }
>     };
>
>     return optimizationMatrix[taskComplexity]?.[budgetConstraint] || "gpt-4.1-mini";
> }
>
> // Example usage
> const model = optimizeModelSelection("high", "flexible");
> console.log(`Optimized model: ${model}`);
> ```

## Error Handling

> [tab] Python
>
> ```python theme={null}
> def get_available_models_with_fallback():
>     """Get available models with proper error handling"""
>     try:
>         response = requests.get(
>             f"{BASE_URL}/v1/models/available",
>             headers=headers,
>             timeout=10
>         )
>
>         if response.status_code == 200:
>             data = response.json()
>             if data.get("success"):
>                 return data.get("models", [])
>             else:
>                 print("❌ API returned success=false")
>                 return []
>         elif response.status_code == 401:
>             print("❌ Authentication failed. Check your API key.")
>             return []
>         elif response.status_code == 429:
>             print("❌ Rate limit exceeded. Please wait before retrying.")
>             return []
>         else:
>             print(f"❌ HTTP {response.status_code}: {response.text}")
>             return []
>
>     except requests.exceptions.Timeout:
>         print("❌ Request timed out")
>         return []
>     except requests.exceptions.ConnectionError:
>         print("❌ Connection error")
>         return []
>     except Exception as e:
>         print(f"❌ Unexpected error: {e}")
>         return []
>
> # Use with fallback
> models = get_available_models_with_fallback()
> if models:
>     print(f"Available models: {len(models)}")
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> async function getAvailableModelsWithFallback() {
>     try {
>         const controller = new AbortController();
>         const timeoutId = setTimeout(() => controller.abort(), 10000);
>
>         const response = await fetch(`${BASE_URL}/v1/models/available`, {
>             method: 'GET',
>             headers: headers,
>             signal: controller.signal
>         });
>
>         clearTimeout(timeoutId);
>
>         if (!response.ok) {
>             if (response.status === 401) {
>                 console.log("❌ Authentication failed. Check your API key.");
>             } else if (response.status === 429) {
>                 console.log("❌ Rate limit exceeded. Please wait before retrying.");
>             } else {
>                 console.log(`❌ HTTP ${response.status}: ${await response.text()}`);
>             }
>             return [];
>         }
>
>         const data = await response.json();
>
>         if (!data.success) {
>             console.log("❌ API returned success=false");
>             return [];
>         }
>
>         return data.models || [];
>
>     } catch (error) {
>         if (error.name === 'AbortError') {
>             console.log("❌ Request timed out");
>         } else if (error.name === 'TypeError') {
>             console.log("❌ Connection error");
>         } else {
>             console.log(`❌ Unexpected error: ${error.message}`);
>         }
>         return [];
>     }
> }
>
> // Use with fallback
> getAvailableModelsWithFallback().then(models => {
>     if (models.length > 0) {
>         console.log(`Available models: ${models.length}`);
>     }
> });
> ```

## Best Practices

1. **Cache Results**: Cache the models list to avoid frequent API calls
2. **Handle Changes**: Models may be added or removed over time
3. **Fallback Logic**: Always have fallback models for reliability
4. **Version Awareness**: Be aware of model versioning and deprecation
5. **Cost Monitoring**: Track usage costs for different models; each model has its own price per 1M tokens
6. **Performance Testing**: Test model performance for your specific use cases
7. **Documentation Review**: Check model-specific limitations and capabilities

## Integration Examples

### Model Selection in Agent Creation

```python theme={null}
def create_agent_with_best_model(task_type):
    """Create an agent with the best available model for the task"""
    models = get_available_models()
    best_model = select_best_model(task_type)

    return {
        "agent_config": {
            "agent_name": f"{task_type.title()} Agent",
            "model_name": best_model,
            "max_tokens": 2048,
            "temperature": 0.7
        },
        "task": f"Perform {task_type} task"
    }
```

### Batch Processing with Model Optimization

```python theme={null}
def optimize_batch_processing(tasks):
    """Optimize model selection for batch processing"""
    optimized_payloads = []

    for task in tasks:
        task_type = classify_task(task)
        best_model = select_best_model(task_type, "cost")
        optimized_payloads.append({
            "agent_config": {
                "agent_name": f"Optimized Agent {len(optimized_payloads) + 1}",
                "model_name": best_model,
                "max_tokens": 1024
            },
            "task": task
        })

    return optimized_payloads
```


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