## Error Response Format

When an error occurs, the API returns a JSON object with an `error` field:

```json
{
  "error": {
    "message": "A human-readable error description",
    "type": "error_type",
    "code": 400
  }
}
```

## Error Codes

| HTTP Code | Type                    | Description                                              |
| --------- | ----------------------- | -------------------------------------------------------- |
| `400`     | `invalid_request_error` | The request body is malformed or missing required fields |
| `401`     | `authentication_error`  | Invalid or missing API key                               |
| `402`     | `insufficient_balance`  | Your eligible wallet balance is exhausted                |
| `404`     | `not_found`             | The requested resource doesn't exist                     |
| `429`     | `rate_limit_error`      | You've exceeded your current rate limit                  |
| `500`     | `internal_error`        | An unexpected error occurred on our end                  |

## Common Errors

### 400 — Invalid Model

```json
{
  "error": {
    "message": "Unsupported model: \"gpt-4\". See the documentation for the full list of supported models.",
    "type": "invalid_request_error",
    "code": 400
  }
}
```

**Fix:** Check the [supported models list](/docs/models/supported-models) and use a valid model ID.

### 400 — Missing Model Field

```json
{
  "error": {
    "message": "Model field is required in request body",
    "type": "invalid_request_error",
    "code": 400
  }
}
```

### 401 — Invalid API Key

```json
{
  "error": {
    "message": "Invalid API key provided",
    "type": "authentication_error",
    "code": 401
  }
}
```

**Fix:** Check that your API key is correct and starts with `sk_`. Generate a new key from your [dashboard](https://modelstack.cc/dashboard) if needed.

### 402 — Insufficient Balance

```json
{
  "error": {
    "message": "Insufficient balance. Please add balance.",
    "type": "insufficient_balance",
    "code": 402
  }
}
```

**Fix:** Purchase prepaid balance from your [dashboard](https://modelstack.cc/dashboard/billing).

### 429 — Rate Limit Exceeded

```json
{
  "error": {
    "message": "Rate limit exceeded. Please retry after a short delay.",
    "type": "rate_limit_error",
    "code": 429
  }
}
```

**Fix:** Implement exponential backoff and check your dashboard for account details.

### 500 — Internal Server Error

```json
{
  "error": {
    "message": "An internal error occurred. Please try again later.",
    "type": "internal_error",
    "code": 500
  }
}
```

**Fix:** Retry with exponential backoff. If the problem persists, contact support.

## Error Handling Best Practices

<AccordionGroup>
  <Accordion title="Implement retry logic with exponential backoff">
    For `429` and `500` errors, retry with increasing delays:

    ```python
    import time
    from openai import OpenAI, RateLimitError, APIError

    client = OpenAI(
        api_key="your_api_key",
        base_url="https://api.modelstack.cc/v1"
    )

    def make_request_with_retry(messages, max_retries=3):
        for attempt in range(max_retries):
            try:
                return client.chat.completions.create(
                    model="claude-sonnet-4-6",
                    messages=messages
                )
            except RateLimitError:
                time.sleep(2 ** attempt)
            except APIError as e:
                if e.status_code == 500:
                    time.sleep(2 ** attempt)
                else:
                    raise
        raise Exception("Max retries exceeded")
    ```

  </Accordion>
  <Accordion title="Handle insufficient balance gracefully">
    Check for `402` errors and notify users to add balance:

    ```python
    try:
        response = client.chat.completions.create(
            model="claude-sonnet-4-6",
            messages=[{"role": "user", "content": "Hello"}]
        )
    except Exception as e:
        if "402" in str(e):
            print("Out of balance. Visit your dashboard to top up.")
    ```

  </Accordion>
  <Accordion title="Validate models before sending requests">
    Use the `/v1/models` endpoint to check if a model is supported before making a chat completion request.
  </Accordion>
</AccordionGroup>
