Error Codes Reference

Quick Access: Error Tracking | Request Logs

This guide explains LangMart API error codes and how to handle them.

Error Response Format

All errors follow a consistent format:

{
  "error": {
    "type": "error_type",
    "code": "error_code",
    "message": "Human-readable description",
    "param": "field_name",
    "details": {}
  }
}
Field Description
type Error category
code Specific error code
message Human-readable description
param Related parameter (if applicable)
details Additional error context

HTTP Status Codes

Status Category Description
200 Success Request succeeded
201 Created Resource created
400 Bad Request Invalid request format
401 Unauthorized Authentication failed
402 Payment Required Insufficient credits
403 Forbidden Permission denied
404 Not Found Resource not found
429 Too Many Requests Rate limit exceeded
500 Server Error Internal error
502 Bad Gateway Provider communication error
503 Service Unavailable Service temporarily down
504 Gateway Timeout Request timed out

Authentication Errors (401)

invalid_api_key

{
  "error": {
    "type": "authentication_error",
    "code": "invalid_api_key",
    "message": "Invalid API key provided"
  }
}

Cause: The API key is incorrect or malformed.

Solution:

  • Check that the key is copied correctly
  • Ensure no extra spaces or characters
  • Verify the key hasn't been deleted

expired_api_key

{
  "error": {
    "type": "authentication_error",
    "code": "expired_api_key",
    "message": "API key has expired"
  }
}

Solution:

  • Create a new API key in Settings
  • Update your application with the new key

missing_api_key

{
  "error": {
    "type": "authentication_error",
    "code": "missing_api_key",
    "message": "No API key provided in request"
  }
}

Solution: Add the Authorization header:

Authorization: Bearer YOUR_API_KEY

Billing Errors (402)

insufficient_credits

{
  "error": {
    "type": "billing_error",
    "code": "insufficient_credits",
    "message": "Insufficient credits. Your balance ($0.05) is below the minimum required ($0.10).",
    "details": {
      "current_balance": 0.05,
      "minimum_required": 0.10
    }
  }
}

Solution:

payment_required

{
  "error": {
    "type": "billing_error",
    "code": "payment_required",
    "message": "Payment method required to continue"
  }
}

Solution: Add a payment method in your account settings.


Permission Errors (403)

insufficient_permissions

{
  "error": {
    "type": "authorization_error",
    "code": "insufficient_permissions",
    "message": "API key lacks required permissions: admin",
    "details": {
      "required": ["admin"],
      "current": ["read", "write"]
    }
  }
}

Solution:

  • Use an API key with the required permissions
  • Contact your organization admin

model_access_denied

{
  "error": {
    "type": "authorization_error",
    "code": "model_access_denied",
    "message": "You don't have access to this model",
    "details": {
      "model": "openai/gpt-4o"
    }
  }
}

Solution:

  • Check if you have a connection for this provider
  • Contact your organization admin to request access

organization_required

{
  "error": {
    "type": "authorization_error",
    "code": "organization_required",
    "message": "This model requires organization membership"
  }
}

Solution: Join an organization that provides access to this model.


Request Errors (400)

invalid_request

{
  "error": {
    "type": "invalid_request_error",
    "code": "invalid_request",
    "message": "Invalid request format",
    "param": "messages",
    "details": {
      "issue": "messages array is required"
    }
  }
}

Solution: Check the request format matches the API specification.

invalid_model

{
  "error": {
    "type": "invalid_request_error",
    "code": "invalid_model",
    "message": "Invalid model ID format. Expected: provider/model",
    "param": "model"
  }
}

Solution: Use the format provider/model, e.g., openai/gpt-4o.

context_length_exceeded

{
  "error": {
    "type": "invalid_request_error",
    "code": "context_length_exceeded",
    "message": "Request exceeds model's context length",
    "details": {
      "max_context": 128000,
      "requested": 150000
    }
  }
}

Solution:

  • Reduce the conversation length
  • Use a model with larger context window
  • Implement conversation summarization

max_tokens_exceeded

{
  "error": {
    "type": "invalid_request_error",
    "code": "max_tokens_exceeded",
    "message": "max_tokens exceeds model limit",
    "details": {
      "max_allowed": 16384,
      "requested": 20000
    }
  }
}

Solution: Reduce the max_tokens parameter.


Not Found Errors (404)

model_not_found

{
  "error": {
    "type": "not_found_error",
    "code": "model_not_found",
    "message": "Model not found: invalid/model-name"
  }
}

Solution:

resource_not_found

{
  "error": {
    "type": "not_found_error",
    "code": "resource_not_found",
    "message": "Resource not found"
  }
}

Solution: Verify the resource ID exists.


Rate Limit Errors (429)

rate_limit_exceeded

{
  "error": {
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Please retry after 60 seconds.",
    "details": {
      "limit": 60,
      "window": "1m",
      "retry_after": 60
    }
  }
}

Headers:

X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1704067260
Retry-After: 60

Solution:

import time

def make_request_with_retry(func, max_retries=3):
    for attempt in range(max_retries):
        try:
            return func()
        except RateLimitError as e:
            retry_after = int(e.response.headers.get('Retry-After', 60))
            time.sleep(retry_after)
    raise Exception("Max retries exceeded")

tokens_per_minute_exceeded

{
  "error": {
    "type": "rate_limit_error",
    "code": "tokens_per_minute_exceeded",
    "message": "Token rate limit exceeded",
    "details": {
      "limit": 150000,
      "used": 155000
    }
  }
}

Solution:

  • Wait for the rate limit window to reset
  • Reduce request size
  • Spread requests over time

Gateway Errors (502, 503)

gateway_unavailable

{
  "error": {
    "type": "gateway_error",
    "code": "gateway_unavailable",
    "message": "No gateway available to handle request"
  }
}

Solution:

  • Check your connections at Connections
  • Verify provider status
  • Wait and retry

provider_error

{
  "error": {
    "type": "gateway_error",
    "code": "provider_error",
    "message": "Provider returned an error",
    "details": {
      "provider": "openai",
      "provider_error": "Service temporarily unavailable"
    }
  }
}

Solution:

  • Check provider status page
  • Use a different provider/model
  • Implement retry logic

connection_failed

{
  "error": {
    "type": "gateway_error",
    "code": "connection_failed",
    "message": "Failed to connect to provider"
  }
}

Solution:

  • Test your connection at Connections
  • Verify API key is valid
  • Check for provider outages

Timeout Errors (504)

request_timeout

{
  "error": {
    "type": "timeout_error",
    "code": "request_timeout",
    "message": "Request timed out after 120 seconds"
  }
}

Solution:

  • Reduce response length (lower max_tokens)
  • Use streaming for long responses
  • Use a faster model (e.g., Groq)

Server Errors (500)

internal_error

{
  "error": {
    "type": "server_error",
    "code": "internal_error",
    "message": "An internal error occurred",
    "request_id": "req_abc123"
  }
}

Solution:

  • Retry the request
  • If persistent, contact support with the request_id

Error Handling Best Practices

Python Example

from openai import OpenAI, APIError, RateLimitError, AuthenticationError
import time

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.langmart.ai/v1"
)

def make_request(messages, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="openai/gpt-4o",
                messages=messages
            )
        except AuthenticationError:
            raise  # Don't retry auth errors
        except RateLimitError as e:
            if attempt == max_retries - 1:
                raise
            retry_after = int(e.response.headers.get('Retry-After', 60))
            print(f"Rate limited, waiting {retry_after}s...")
            time.sleep(retry_after)
        except APIError as e:
            if e.status_code >= 500 and attempt < max_retries - 1:
                wait = 2 ** attempt
                print(f"Server error, retrying in {wait}s...")
                time.sleep(wait)
            else:
                raise

# Usage
try:
    response = make_request([{"role": "user", "content": "Hello"}])
    print(response.choices[0].message.content)
except AuthenticationError:
    print("Invalid API key")
except RateLimitError:
    print("Rate limit exceeded")
except APIError as e:
    print(f"API error: {e.message}")

JavaScript Example

import OpenAI from 'openai';

const client = new OpenAI({
    apiKey: 'YOUR_API_KEY',
    baseURL: 'https://api.langmart.ai/v1'
});

async function makeRequest(messages, maxRetries = 3) {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
        try {
            return await client.chat.completions.create({
                model: 'openai/gpt-4o',
                messages
            });
        } catch (error) {
            if (error.status === 401) {
                throw error; // Don't retry auth errors
            }
            if (error.status === 429) {
                const retryAfter = error.headers?.['retry-after'] || 60;
                console.log(`Rate limited, waiting ${retryAfter}s...`);
                await new Promise(r => setTimeout(r, retryAfter * 1000));
            } else if (error.status >= 500 && attempt < maxRetries - 1) {
                const wait = Math.pow(2, attempt);
                console.log(`Server error, retrying in ${wait}s...`);
                await new Promise(r => setTimeout(r, wait * 1000));
            } else {
                throw error;
            }
        }
    }
    throw new Error('Max retries exceeded');
}