BLACKFUEL
Guides

Error Handling

The Blackfuel API error object, its status codes, and the retry pattern for each

Error Response Format

Errors carry a structured error object, with two exceptions that return plain text: a 413 and a 524.

{
  "error": {
    "type": "error_type",
    "message": "Human-readable error description",
    "param": "parameter_name",
    "code": "specific_error_code"
  }
}
FieldTypeDescription
typestringError category
messagestringDetailed error description
paramstring | nullParameter that caused the error, or null when not tied to one
codestringSpecific error code (if applicable)

This includes authentication rejections (401), so the OpenAI SDKs and any tooling that switches on error.code work consistently across every error that carries the error object.

HTTP Status Codes

Client Errors (4xx)

StatusTypeDescription
400invalid_request_errorInvalid parameters or malformed request
401invalid_request_errorNo API key (code: null) or an invalid/revoked key (code: invalid_api_key)
402insufficient_quotaInsufficient account balance
404invalid_request_errorUnknown model (code: model_not_found)
413—Request body too large; see Request Limits
422invalid_request_errorAn image_url in the request could not be fetched
429rate_limit_errorToo many requests; see Rate Limits

Server Errors (5xx)

StatusTypeDescription
500internal_errorUnexpected server error
503service_unavailableService temporarily unavailable
504gateway_timeoutRequest timed out
524—Response timeout exceeded. See Timeouts and Long-Running Requests

Common Errors and Solutions

Authentication and Billing Errors

401 - No API Key (code: null)

{
  "error": {
    "message": "No API key provided. Provide your key in the Authorization header as 'Bearer <YOUR_API_KEY>'. Manage your keys at https://console.blackfuel.ai.",
    "type": "invalid_request_error",
    "param": null,
    "code": null
  }
}

Solution: Include your API key in the Authorization: Bearer header.

401 - Invalid API Key (code: invalid_api_key)

{
  "error": {
    "message": "Incorrect API key provided. Check the key for typos or whether it has been revoked. Manage your keys at https://console.blackfuel.ai.",
    "type": "invalid_request_error",
    "param": null,
    "code": "invalid_api_key"
  }
}

Solution: Verify your API key is correct and hasn't been revoked. A missing key and an invalid key both return 401; error.code distinguishes them (null vs invalid_api_key).

402 - Insufficient Balance

{
  "error": {
    "message": "Your account has insufficient balance to process this request. Add credit at https://console.blackfuel.ai or contact [email protected].",
    "type": "insufficient_quota",
    "code": "insufficient_quota",
    "param": null
  }
}

Solution: Add credit to your account in the console.

Invalid Request Errors

400 - Invalid Parameters

{
  "error": {
    "message": "temperature must be in [0, 2], got 99.0. (parameter=temperature, value=99.0)",
    "type": "invalid_request_error",
    "param": "temperature",
    "code": null
  }
}

Solution: Check parameter constraints in the API documentation.

413 - Payload Too Large

Payload Too Large

Solution: See Request Limits for the limit and how to bring a request under it.

422 - Image Could Not Be Fetched

{
  "error": {
    "message": "Failed to fetch media from URL: HTTP 404 error (parameter=image_url, value=https://example.com/image.jpg)",
    "type": "invalid_request_error",
    "param": "image_url",
    "code": null
  }
}

Solution: Check that the URL is publicly reachable over HTTPS and returns the image, or send the image inline as a data: URI.

404 - Model Not Found (code: model_not_found)

{
  "error": {
    "message": "The model does not exist or you do not have access to it.",
    "type": "invalid_request_error",
    "param": null,
    "code": "model_not_found"
  }
}

Solution: Use a valid model ID from the models list. A request for a model that is not served returns 404 with code: model_not_found.

Rate Limit Errors

A 429 comes in two shapes, distinguished by error.code.

429 - Rate Limit Exceeded (code: rate_limit_exceeded)

Your quota is exhausted.

{
  "error": {
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "message": "Quota exceeded. Please try again later.",
    "param": null
  }
}

Solution: Retry after the retry-after interval — see Rate Limits for the header and the retry pattern.

429 - Overloaded (code: overloaded)

The platform is at capacity.

{
  "error": {
    "type": "rate_limit_error",
    "code": "overloaded",
    "message": "The platform is currently overloaded — please retry with backoff.",
    "param": null
  }
}

Solution: Retry with exponential backoff — see Rate Limits.

Service Errors

503 - Service Unavailable

{
  "error": {
    "type": "service_unavailable",
    "message": "The service is temporarily unavailable. Please try again later."
  }
}

Solution: Wait and retry with exponential backoff.

504 - Gateway Timeout

{
  "error": {
    "type": "gateway_timeout",
    "message": "Request timed out."
  }
}

Solution: Retry after a few seconds.

Timeouts and Long-Running Requests

A non-streaming request that produces no response before the response timeout fails with a 524. Use streaming for any request that may run that long — Timeouts and Long-Running Requests gives both limits, their exact values, and why streaming clears them.

A 524 does not carry the JSON error envelope above — its body is the plain text error code: 524, so code that assumes every failure parses as JSON breaks on it.

Error Handling in Code

Python

import os
import time

import openai
from openai import (
    APIError,
    AuthenticationError,
    PermissionDeniedError,
    RateLimitError,
    APIConnectionError,
)

client = openai.OpenAI(
    base_url="https://api.blackfuel.ai/v1",
    api_key=os.environ["BLACKFUEL_API_KEY"],
)

def chat_completion(messages, retries=3):
    for attempt in range(retries):
        try:
            return client.chat.completions.create(
                model="deepseek-ai/DeepSeek-V4-Flash-0731",
                messages=messages
            )

        except (AuthenticationError, PermissionDeniedError) as e:
            # Missing or invalid API key (401) - don't retry
            print(f"Authentication failed: {e}")
            raise

        except RateLimitError as e:
            # Rate limited - wait and retry
            if attempt < retries - 1:
                wait_time = 2 ** attempt
                print(f"Rate limited. Waiting {wait_time}s...")
                time.sleep(wait_time)
            else:
                raise

        except APIConnectionError as e:
            # Network error - retry
            if attempt < retries - 1:
                print(f"Connection error. Retrying...")
                time.sleep(1)
            else:
                raise

        except APIError as e:
            # Server error - retry for 5xx errors
            if e.status_code >= 500 and attempt < retries - 1:
                print(f"Server error {e.status_code}. Retrying...")
                time.sleep(2 ** attempt)
            else:
                raise

JavaScript

import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://api.blackfuel.ai/v1',
  apiKey: process.env.BLACKFUEL_API_KEY
});

async function chatCompletion(messages, retries = 3) {
  for (let attempt = 0; attempt < retries; attempt++) {
    try {
      return await client.chat.completions.create({
        model: 'deepseek-ai/DeepSeek-V4-Flash-0731',
        messages
      });

    } catch (error) {
      // Authentication (401) or insufficient balance (402) - don't retry
      if ([401, 402].includes(error.status)) {
        console.error('Non-retryable error:', error.message);
        throw error;
      }

      // Rate limit - wait and retry
      if (error.status === 429 && attempt < retries - 1) {
        const waitTime = Math.pow(2, attempt) * 1000;
        console.log(`Rate limited. Waiting ${waitTime}ms...`);
        await new Promise(r => setTimeout(r, waitTime));
        continue;
      }

      // Server error - retry for 5xx
      if (error.status >= 500 && attempt < retries - 1) {
        const waitTime = Math.pow(2, attempt) * 1000;
        console.log(`Server error. Waiting ${waitTime}ms...`);
        await new Promise(r => setTimeout(r, waitTime));
        continue;
      }

      throw error;
    }
  }
}

Best Practices

1. Always Handle Errors

Never assume API calls will succeed. Wrap all calls in try-catch blocks.

2. Implement Retries with Backoff

Use exponential backoff for transient errors:

wait_time = base_wait * (2 ** attempt)  # e.g., 1, 2, 4, 8 seconds

3. Distinguish Error Types

  • Authentication errors - Fix configuration, don't retry
  • Invalid request errors - Fix request, don't retry
  • Insufficient balance - Add credit, don't retry
  • Rate limits - Wait and retry
  • Server errors - Retry with backoff

4. Log Errors for Debugging

Include request IDs and timestamps in your logs:

except APIError as e:
    logger.error(f"API error: {e.status_code} - {e.message}")

5. Set Appropriate Timeouts

Size client timeouts to the platform limits; Client timeouts covers sizing read timeouts for streaming and non-streaming requests.

import os

import httpx
import openai

client = openai.OpenAI(
    base_url="https://api.blackfuel.ai/v1",
    api_key=os.environ["BLACKFUEL_API_KEY"],
    timeout=httpx.Timeout(600.0, connect=5.0),
)

6. Handle Partial Failures in Streaming

For streaming requests, handle disconnections gracefully:

try:
    for chunk in stream:
        process(chunk)
except Exception as e:
    # Save progress and optionally retry
    handle_stream_error(e)

On this page