API Reference
Errors

Error Codes Reference

Complete reference for all Avatarium API error codes with descriptions and solutions.

Error Response Format

All errors follow a consistent JSON structure:

{
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable description of the error"
  },
  "meta": {
    "requestId": "req_abc123xyz"
  }
}

Some errors include additional fields:

{
  "error": {
    "code": "FREE_TIER_LIMIT_EXCEEDED",
    "message": "You've used 100 of your 100 free messages this month."
  },
  "upgrade": true,
  "byokRequired": true,
  "usage": {
    "used": 100,
    "limit": 100,
    "remaining": 0
  }
}

HTTP Status Codes

CodeDescriptionAction
200SuccessRequest completed
400Bad RequestFix request parameters
401UnauthorizedCheck authentication
403ForbiddenCheck permissions or quota
404Not FoundVerify resource exists
429Rate LimitedWait and retry with backoff
500Server ErrorRetry with backoff
503Service UnavailableProvider issue, retry later

Authentication Errors (401)

UNAUTHORIZED

Missing or invalid authentication credentials.

{
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Authentication required. Provide an API key or JWT token."
  }
}

Solutions:

  • Ensure Authorization header is set
  • Use format: Authorization: Bearer av_live_xxxxx
  • Check the API key is valid in dashboard

INVALID_API_KEY

The provided API key is not valid.

{
  "error": {
    "code": "INVALID_API_KEY",
    "message": "The provided API key is invalid or has been revoked"
  }
}

Solutions:

  • Verify the key in your dashboard
  • Check for extra whitespace
  • Regenerate the key if needed

TOKEN_EXPIRED

JWT authentication token has expired.

{
  "error": {
    "code": "TOKEN_EXPIRED",
    "message": "Your authentication token has expired. Please sign in again."
  }
}

Solutions:

  • Refresh the Firebase token
  • Sign in again

TOKEN_INVALID

JWT token signature verification failed.

{
  "error": {
    "code": "TOKEN_INVALID",
    "message": "Invalid authentication token"
  }
}

Solutions:

  • Ensure token is from correct Firebase project
  • Check token hasn't been tampered with

Request Errors (400)

INVALID_REQUEST

Request body is malformed or missing required fields.

{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "Request body must be valid JSON"
  }
}

Solutions:

  • Verify JSON syntax
  • Check Content-Type header is application/json

MISSING_PARAMETER

A required parameter was not provided.

{
  "error": {
    "code": "MISSING_PARAMETER",
    "message": "avatar_id is required"
  }
}

Solutions:

  • Check API documentation for required fields
  • Ensure all required parameters are included

INVALID_PARAMETER

A parameter value is invalid or out of range.

{
  "error": {
    "code": "INVALID_PARAMETER",
    "message": "Invalid voice ID format"
  }
}

Solutions:

  • Check parameter format requirements
  • Verify values are within valid ranges

INVALID_SLUG

Avatar or account slug format is invalid.

{
  "error": {
    "code": "INVALID_SLUG",
    "message": "Slug must contain only lowercase letters, numbers, and hyphens"
  }
}

Solutions:

  • Use only: a-z, 0-9, -
  • No spaces or special characters
  • 3-50 characters length

Permission Errors (403)

FORBIDDEN

User doesn't have permission for this action.

{
  "error": {
    "code": "FORBIDDEN",
    "message": "You don't have permission to access this resource"
  }
}

Solutions:

  • Verify you own the resource
  • Check API key permissions

FREE_TIER_LIMIT_EXCEEDED

Message quota exhausted.

{
  "error": {
    "code": "FREE_TIER_LIMIT_EXCEEDED",
    "message": "You've used 100 of your 100 free messages this month. Provide your own API key (BYOK) to continue, or upgrade your plan."
  },
  "upgrade": true,
  "byokRequired": true,
  "usage": {
    "used": 100,
    "limit": 100,
    "remaining": 0
  }
}

Solutions:

  • Add BYOK keys to bypass limit: byokAI and byokTTS props
  • Upgrade to a paid plan
  • Wait for monthly reset

Your plan message limit has been reached. Use BYOK for unlimited usage.

AVATAR_LIMIT_EXCEEDED

Maximum avatars created for current plan.

{
  "error": {
    "code": "AVATAR_LIMIT_EXCEEDED",
    "message": "You've reached the maximum number of avatars for your plan (5/5)"
  }
}

Solutions:

  • Delete unused avatars
  • Upgrade to a higher plan

Resource Errors (404)

AVATAR_NOT_FOUND

The requested avatar doesn't exist.

{
  "error": {
    "code": "AVATAR_NOT_FOUND",
    "message": "Avatar not found"
  }
}

Solutions:

  • Verify the avatar ID is correct
  • Check avatar hasn't been deleted
  • Ensure you have access to the avatar

CONVERSATION_NOT_FOUND

The conversation doesn't exist or has expired.

{
  "error": {
    "code": "CONVERSATION_NOT_FOUND",
    "message": "Conversation not found or expired"
  }
}

Solutions:

  • Create a new conversation
  • Conversations may expire after inactivity

SESSION_NOT_FOUND

Avatar session doesn't exist.

{
  "error": {
    "code": "SESSION_NOT_FOUND",
    "message": "Session not found. Create a new session first."
  }
}

Solutions:

  • Call the session creation endpoint first
  • Sessions may timeout after 30 minutes

ACCOUNT_NOT_FOUND

Account with the given slug doesn't exist.

{
  "error": {
    "code": "ACCOUNT_NOT_FOUND",
    "message": "Account not found"
  }
}

Solutions:

  • Verify the account slug
  • Check URL formatting

Rate Limit Errors (429)

RATE_LIMIT_EXCEEDED

Too many requests in a short period.

{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Please wait before making more requests."
  }
}

Headers included:

X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1705312800
Retry-After: 45

Solutions:

  • Wait for Retry-After seconds
  • Implement exponential backoff
  • Upgrade plan for higher limits

AUTH_RATE_LIMIT_EXCEEDED

Too many authentication attempts.

{
  "error": {
    "code": "AUTH_RATE_LIMIT",
    "message": "Too many login attempts. Please try again in 60 seconds."
  }
}

Limits by operation:

OperationLimitWindow
Password attempts51 minute
Login attempts101 minute
Account creation35 minutes

Solutions:

  • Wait for the specified time
  • Contact support if legitimate use is blocked

Provider Errors (503)

AI_PROVIDER_ERROR

AI service (OpenAI, Anthropic, etc.) is unavailable.

{
  "error": {
    "code": "AI_PROVIDER_ERROR",
    "message": "AI service temporarily unavailable"
  }
}

Solutions:

  • Retry with exponential backoff
  • Check provider status pages
  • Try a different AI provider via BYOK

TTS_PROVIDER_ERROR

Text-to-speech service is unavailable.

{
  "error": {
    "code": "TTS_PROVIDER_ERROR",
    "message": "TTS service temporarily unavailable"
  }
}

Solutions:

  • Retry after a few seconds
  • Check ElevenLabs/Google Cloud status
  • Switch TTS provider via BYOK

BYOK_PROVIDER_ERROR

Customer's BYOK API key failed.

{
  "error": {
    "code": "BYOK_PROVIDER_ERROR",
    "message": "Your OpenAI API key returned an error: insufficient_quota"
  }
}

Solutions:

  • Check your provider account for quota/billing
  • Verify API key is valid
  • Check provider-specific error message

Configuration Errors (500)

CONFIG_ERROR

Server configuration issue.

{
  "error": {
    "code": "CONFIG_ERROR",
    "message": "Service not configured. Please contact support."
  }
}

Solutions:

  • Contact support
  • This is typically a server-side issue

INTERNAL_ERROR

Unexpected server error.

{
  "error": {
    "code": "INTERNAL_ERROR",
    "message": "An unexpected error occurred"
  }
}

Solutions:

  • Retry the request
  • Contact support with requestId if persistent

Error Handling Best Practices

Implement Retry Logic

async function fetchWithRetry(url: string, options: RequestInit, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    const response = await fetch(url, options);
 
    if (response.ok) return response.json();
 
    const error = await response.json();
 
    // Don't retry client errors (4xx) except rate limits
    if (response.status < 500 && response.status !== 429) {
      throw new Error(error.error.message);
    }
 
    // Get retry delay from header or use exponential backoff
    const retryAfter = response.headers.get('Retry-After');
    const delay = retryAfter
      ? parseInt(retryAfter) * 1000
      : Math.pow(2, attempt) * 1000;
 
    await new Promise(r => setTimeout(r, delay));
  }
  throw new Error('Max retries exceeded');
}

Log Request IDs

Always log the requestId from error responses for debugging:

try {
  const result = await sendMessage(content);
} catch (error) {
  console.error('API Error:', {
    code: error.code,
    message: error.message,
    requestId: error.meta?.requestId  // Include this when contacting support
  });
}

Handle BYOK Errors Gracefully

<AvatariumEmbed
  shortId="YOUR_SHORT_ID"
  onError={(errorMessage) => {
    if (errorMessage.includes('BYOK_PROVIDER_ERROR')) {
      // Fall back to platform AI or show upgrade prompt
      console.warn('BYOK failed, check your OpenAI account');
    }
  }}
/>

SDK Error Codes

The Avatarium SDK uses structured error codes for client-side error handling. These codes start with E followed by a number and are thrown by the AvatariumError class.

Using AvatariumError

import { AvatariumError, AvatariumErrorCode } from '@avatarium/react';
 
try {
  // AvatariumError is thrown by provider operations, e.g. inside a custom AI/TTS hook
  throw new AvatariumError(AvatariumErrorCode.CONNECTION_FAILED);
} catch (error) {
  if (error instanceof AvatariumError) {
    console.log('Error code:', error.code);        // e.g., 'E001'
    console.log('Recoverable:', error.recoverable); // true/false
    console.log('Retry after:', error.retryAfter);  // milliseconds
 
    // Handle specific error codes
    switch (error.code) {
      case AvatariumErrorCode.CONNECTION_FAILED:
        // Retry connection
        break;
      case AvatariumErrorCode.API_KEY_INVALID:
        // Prompt user to check API key
        break;
    }
  }
}

Connection Errors (E001-E010)

CodeNameMessageRecoverable
E001CONNECTION_FAILEDFailed to establish connection to the server✅ Yes
E002WEBSOCKET_CLOSEDWebSocket connection was closed unexpectedly✅ Yes
E003WEBSOCKET_ERRORWebSocket encountered an error✅ Yes
E004NETWORK_ERRORNetwork request failed✅ Yes
E005TIMEOUTOperation timed out✅ Yes

Solutions:

  • Check internet connectivity
  • Verify firewall isn't blocking WebSocket connections
  • Implement automatic retry with exponential backoff
  • The SDK will attempt to reconnect automatically for recoverable errors

Authentication Errors (E011-E020)

CodeNameMessageRecoverable
E011API_KEY_INVALIDThe provided API key is invalid❌ No
E012API_KEY_EXPIREDThe API key has expired❌ No
E013API_KEY_MISSINGAPI key is required but was not provided❌ No
E014BYOK_KEY_INVALIDThe BYOK API key is invalid or rejected by the provider❌ No
E015BYOK_KEY_EXPIREDThe BYOK API key has expired❌ No
E016UNAUTHORIZEDNot authorized to perform this action❌ No

Solutions:

  • Verify API key in your dashboard at dashboard.avatarium.ai
  • Regenerate the API key if expired
  • For BYOK errors, check your provider's console (OpenAI, Anthropic, etc.)
  • Ensure you're using the correct key type (live vs test)

Avatar Errors (E021-E030)

CodeNameMessageRecoverable
E021AVATAR_LOAD_FAILEDFailed to load the avatar model✅ Yes
E022AVATAR_NOT_FOUNDThe specified avatar was not found❌ No
E023AVATAR_NOT_INITIALIZEDAvatar has not been initialized. Call connect() first❌ No
E024AVATAR_MODEL_INVALIDThe avatar model format is invalid or corrupted❌ No
E025CONTAINER_NOT_FOUNDThe specified container element was not found❌ No

Solutions:

  • Ensure the container element exists in the DOM before initializing
  • Verify the avatar ID is correct
  • Call connect() before sending messages
  • Check that 3D model files are accessible and not corrupted

TTS Errors (E031-E040)

CodeNameMessageRecoverable
E031TTS_FAILEDText-to-speech synthesis failed✅ Yes
E032TTS_PROVIDER_ERRORTTS provider returned an error✅ Yes
E033TTS_AUDIO_DECODE_FAILEDFailed to decode TTS audio data✅ Yes
E034TTS_VOICE_NOT_FOUNDThe specified voice was not found❌ No
E035TTS_QUOTA_EXCEEDEDTTS quota has been exceeded❌ No

Solutions:

  • Verify voice ID is valid for the selected TTS provider
  • Check BYOK TTS provider quota and billing
  • Try a different TTS provider or voice
  • Ensure audio format is supported by the browser

AI Errors (E041-E050)

CodeNameMessageRecoverable
E041AI_PROVIDER_ERRORAI provider returned an error✅ Yes
E042AI_MODEL_NOT_FOUNDThe specified AI model was not found❌ No
E043AI_CONTEXT_LENGTH_EXCEEDEDThe conversation context is too long❌ No
E044AI_CONTENT_FILTEREDContent was filtered by the AI provider❌ No
E045AI_QUOTA_EXCEEDEDAI usage quota has been exceeded❌ No

Solutions:

  • For context length errors, start a new conversation or reduce message history
  • Check AI provider quotas (OpenAI, Anthropic, etc.)
  • Review content for policy violations if content was filtered
  • Verify the model name is correct for your provider

Rate Limiting Errors (E051-E060)

CodeNameMessageRecoverable
E051RATE_LIMITEDToo many requests. Please slow down✅ Yes
E052QUOTA_EXCEEDEDUsage quota has been exceeded❌ No

Solutions:

  • Implement exponential backoff (the retryAfter property suggests wait time)
  • Upgrade your plan for higher rate limits
// Example: Handling rate limits
if (error.code === AvatariumErrorCode.RATE_LIMITED && error.recoverable) {
  const delay = error.retryAfter || 1000;
  await new Promise(r => setTimeout(r, delay));
  // Retry the operation
}

Conversation Errors (E061-E070)

CodeNameMessageRecoverable
E061CONVERSATION_NOT_FOUNDThe conversation was not found❌ No
E062CONVERSATION_ENDEDThe conversation has already ended❌ No
E063MESSAGE_SEND_FAILEDFailed to send message✅ Yes
E064ALREADY_PROCESSINGAlready processing a message. Please wait✅ Yes

Solutions:

  • Create a new conversation if the previous one ended or was not found
  • Wait for the current message to complete before sending another
  • Conversations may timeout after extended inactivity (30 minutes)

Configuration Errors (E071-E080)

CodeNameMessageRecoverable
E071INVALID_CONFIGInvalid configuration provided❌ No
E072MISSING_REQUIRED_FIELDA required configuration field is missing❌ No
E073INVALID_PROVIDERThe specified provider is not supported❌ No

Solutions:

  • Check required fields: apiKey and container (or avatarId for React)
  • Verify provider names: 'openai', 'anthropic', 'groq', 'gemini' for AI
  • Verify TTS providers: 'google', 'elevenlabs', 'browser'

Browser/Environment Errors (E081-E090)

CodeNameMessageRecoverable
E081BROWSER_NOT_SUPPORTEDThis browser is not supported❌ No
E082WEBGL_NOT_SUPPORTEDWebGL is not supported in this browser❌ No
E083AUDIO_CONTEXT_FAILEDFailed to create audio context❌ No
E084SPEECH_SYNTHESIS_NOT_SUPPORTEDSpeech synthesis is not supported in this browser❌ No

Solutions:

  • Use a modern browser (Chrome, Firefox, Safari, Edge)
  • Enable WebGL in browser settings
  • Ensure browser has audio permissions
  • Check for browser extensions that might block WebGL or audio

Generic Errors (E091-E100)

CodeNameMessageRecoverable
E091UNKNOWN_ERRORAn unknown error occurred❌ No
E092INTERNAL_ERRORAn internal error occurred❌ No
E093VALIDATION_ERRORValidation failed❌ No

Solutions:

  • Check the error's context property for additional details
  • Contact support with the error details if persistent

Complete Error Handling Example

import { Avatar, AvatariumError, AvatariumErrorCode } from '@avatarium/react';
 
function MyAvatar() {
  const handleError = (error: Error) => {
    if (!AvatariumError.isAvatariumError(error)) {
      console.error('Unexpected error:', error);
      return;
    }
 
    // Log structured error info
    console.error('Avatarium Error:', error.toJSON());
 
    // Handle by category
    const code = error.code;
 
    if (code.startsWith('E00')) {
      // Connection error - retry
      showToast('Connection issue. Retrying...');
    } else if (code.startsWith('E01')) {
      // Auth error - prompt login
      showToast('Please check your API key');
    } else if (code.startsWith('E03') || code.startsWith('E04')) {
      // Provider error - show message
      showToast('Service temporarily unavailable');
    } else if (code === AvatariumErrorCode.RATE_LIMITED) {
      // Rate limit - wait and retry
      const delay = error.retryAfter || 5000;
      setTimeout(() => retryOperation(), delay);
    }
  };
 
  return (
    <Avatar
      apiKey={process.env.NEXT_PUBLIC_AVATARIUM_KEY}
      avatarId="default"
      onError={handleError}
    />
  );
}

Need Help?

If you encounter persistent errors:

  1. Check the requestId in the error response
  2. Review this documentation for the error code
  3. Contact support with the requestId

Related