Skip to main content

SDK Configuration

Production settings for VocaFuse SDKs—timeouts, retry behavior, debug logging, and error handling patterns.

Timeout

Set request timeout in seconds:

from vocafuse import Client
import os

client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET'],
timeout=30 # 30 seconds (default: 10)
)

For long-running operations or slow networks, increase the timeout. For latency-sensitive applications, keep it lower and handle timeouts gracefully.

Retry Configuration

Configure automatic retries for transient failures:

client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET'],
max_retries=3, # Number of retry attempts (default: 2)
retry_delay=1.0 # Initial delay between retries in seconds (default: 0.5)
)

The SDK uses exponential backoff—each retry waits longer than the previous. With max_retries=3 and retry_delay=1.0:

AttemptWait Time
1Immediate
21 second
32 seconds
44 seconds

Note: Only idempotent requests (GET, DELETE) and 5xx errors are retried automatically. POST requests are not retried to avoid duplicate operations.

Debug Logging

Enable verbose logging for development and troubleshooting:

import logging

# Set logging level before creating client
logging.basicConfig(level=logging.DEBUG)

client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET'],
debug=True
)

Debug mode logs:

  • Full request URLs and headers
  • Request/response bodies (credentials redacted)
  • Retry attempts and timing
  • Connection pool status
warning

Disable debug logging in production—it may expose sensitive data in logs.

Error Handling

The SDK raises specific exceptions for different error scenarios:

from vocafuse import (
Client,
VocaFuseError,
AuthenticationError,
RateLimitError,
ValidationError,
NotFoundError
)

client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET']
)

try:
recording = client.recordings.get('rec_123')
except AuthenticationError:
# Invalid API credentials - check your keys
logging.error('Invalid API credentials')
except RateLimitError as e:
# Too many requests - back off and retry
logging.warning(f'Rate limited. Retry after {e.retry_after} seconds')
time.sleep(e.retry_after)
except NotFoundError:
# Resource doesn't exist
logging.warning('Recording not found')
except ValidationError as e:
# Invalid request parameters
logging.error(f'Validation error: {e.message}')
except VocaFuseError as e:
# Catch-all for other API errors
logging.error(f'API error: {e.message}')

Exception Types

ExceptionHTTP StatusDescriptionCommon Causes
AuthenticationError401Invalid API credentialsWrong API key/secret, expired credentials
RateLimitError429Rate limit exceededToo many requests, implement backoff
ValidationError400Invalid request parametersMissing required fields, invalid formats
NotFoundError404Resource not foundInvalid recording ID, deleted resource
VocaFuseError5xxServer errorTransient issues, retry with backoff

Rate Limit Handling

When rate limited, the exception includes retry timing:

except RateLimitError as e:
print(f"Rate limited. Retry after: {e.retry_after} seconds")
print(f"Limit: {e.limit}")
print(f"Remaining: {e.remaining}")

# Implement exponential backoff
time.sleep(e.retry_after)

Django Integration

For Django applications, here's a complete integration pattern:

# views.py
import json
import os
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from vocafuse import Client, AccessToken, RequestValidator

client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET']
)

@require_POST
def generate_token(request):
"""Generate JWT token for frontend SDK authentication."""
user_id = request.user.id

token = AccessToken(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET'],
identity=str(user_id)
)

return JsonResponse(token(expires_in=3600))


@csrf_exempt
@require_POST
def handle_webhook(request):
"""Receive and process VocaFuse webhook events."""
validator = RequestValidator(os.environ['VOCAFUSE_WEBHOOK_SECRET'])

payload = request.body.decode('utf-8')
signature = request.headers.get('X-VocaFuse-Signature')

if not validator.validate(payload, signature):
return JsonResponse({'error': 'Invalid signature'}, status=401)

data = json.loads(payload)

if data['event'] == 'recording.transcribed':
recording_id = data['recording']['id']
# Process transcription...

return JsonResponse({'status': 'received'})
# urls.py
from django.urls import path
from . import views

urlpatterns = [
path('api/vocafuse-token/', views.generate_token, name='vocafuse_token'),
path('api/webhooks/vocafuse/', views.handle_webhook, name='vocafuse_webhook'),
]

Environment-Specific Configuration

Use different settings per environment:

import os

# Determine environment
ENV = os.environ.get('ENVIRONMENT', 'development')

# Environment-specific defaults
CONFIG = {
'development': {
'timeout': 30,
'max_retries': 1,
'debug': True
},
'staging': {
'timeout': 15,
'max_retries': 2,
'debug': True
},
'production': {
'timeout': 10,
'max_retries': 3,
'debug': False
}
}

client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET'],
**CONFIG[ENV]
)

Next Steps