Advanced configuration options for the VerbalisAI JavaScript SDK
Advanced configuration options and settings for the VerbalisAI JavaScript SDK.
import { VerbalisAI } from '@verbalisai/sdk';
// Initialize with basic configuration
const client = new VerbalisAI({
apiKey: 'your-api-key',
baseUrl: 'https://api.verbalisai.com/api',
timeout: 30000,
maxRetries: 3
});
import { VerbalisAI } from '@verbalisai/sdk';
// Advanced client configuration
const client = new VerbalisAI({
apiKey: 'your-api-key',
baseUrl: 'https://api.verbalisai.com/api',
// Request settings
timeout: 60000,
maxRetries: 5,
retryDelay: 1000,
// HTTP client settings
httpClient: {
keepAlive: true,
maxSockets: 20,
maxFreeSockets: 10
},
// Custom headers
defaultHeaders: {
'User-Agent': 'MyApp/1.0 VerbalisAI-JavaScript',
'X-Custom-Header': 'custom-value'
},
// Logging configuration
enableLogging: true,
logLevel: 'info',
logRequests: true,
logResponses: false, // Don't log response bodies for privacy
// Default transcription settings
defaultModel: 'mini',
defaultLanguage: 'auto',
// File upload settings
uploadChunkSize: 8 * 1024 * 1024, // 8MB chunks
uploadTimeout: 300000 // 5 minutes for uploads
});
import { VerbalisAI } from '@verbalisai/sdk';
// Client automatically reads these environment variables
const client = new VerbalisAI(); // No need to pass config explicitly
// Supported environment variables:
// VERBALISAI_API_KEY - Your API key
// VERBALISAI_BASE_URL - API base URL
// VERBALISAI_TIMEOUT - Request timeout in milliseconds
// VERBALISAI_MAX_RETRIES - Maximum retry attempts
// VERBALISAI_LOG_LEVEL - Logging level (debug, info, warn, error)
# .env file
VERBALISAI_API_KEY=your-api-key-here
VERBALISAI_BASE_URL=https://api.verbalisai.com/api
VERBALISAI_TIMEOUT=60000
VERBALISAI_MAX_RETRIES=5
VERBALISAI_LOG_LEVEL=info
VERBALISAI_ENABLE_LOGGING=true
VERBALISAI_DEFAULT_MODEL=pro
VERBALISAI_UPLOAD_CHUNK_SIZE=10485760 # 10MB
import dotenv from 'dotenv';
import { VerbalisAI } from '@verbalisai/sdk';
// Load environment variables from .env file
dotenv.config();
// Client configuration is loaded automatically
const client = new VerbalisAI();
// Or explicitly load custom settings
const client = new VerbalisAI({
apiKey: process.env.CUSTOM_API_KEY,
baseUrl: process.env.CUSTOM_BASE_URL || 'https://api.verbalisai.com/api'
});
import fs from 'fs';
import { VerbalisAI } from '@verbalisai/sdk';
// Load configuration from JSON file
function loadConfigFromJson(configPath) {
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
return new VerbalisAI({
apiKey: config.api_key,
baseUrl: config.base_url || 'https://api.verbalisai.com/api',
timeout: config.timeout || 30000,
maxRetries: config.max_retries || 3,
defaultModel: config.default_model || 'mini'
});
}
// config.json
const configExample = {
"api_key": "your-api-key",
"base_url": "https://api.verbalisai.com/api",
"timeout": 60000,
"max_retries": 5,
"default_model": "pro",
"enable_logging": true,
"log_level": "info"
};
const client = loadConfigFromJson('./config.json');
import fs from 'fs';
import yaml from 'yaml';
import { VerbalisAI } from '@verbalisai/sdk';
// Load configuration from YAML file
function loadConfigFromYaml(configPath) {
const configFile = fs.readFileSync(configPath, 'utf8');
const config = yaml.parse(configFile);
return new VerbalisAI(config.verbalisai);
}
// config.yaml
const yamlExample = `
verbalisai:
api_key: "your-api-key"
base_url: "https://api.verbalisai.com/api"
timeout: 60000
max_retries: 5
default_model: "pro"
enable_logging: true
log_level: "info"
# Default transcription settings
defaults:
model: "pro"
language: "auto"
diarize: false
topics: true
summarization: false
`;
const client = loadConfigFromYaml('./config.yaml');
import { VerbalisAI } from '@verbalisai/sdk';
// Configure logging
const client = new VerbalisAI({
apiKey: 'your-api-key',
enableLogging: true,
logLevel: 'info',
logger: console // Use console or custom logger
});
import winston from 'winston';
import { VerbalisAI } from '@verbalisai/sdk';
// Create custom Winston logger
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
defaultMeta: { service: 'verbalisai-client' },
transports: [
new winston.transports.File({ filename: 'verbalisai-error.log', level: 'error' }),
new winston.transports.File({ filename: 'verbalisai-combined.log' }),
new winston.transports.Console({
format: winston.format.simple()
})
]
});
// Custom logger wrapper for VerbalisAI
class VerbalisAILogger {
debug(message, meta) {
logger.debug(message, meta);
}
info(message, meta) {
logger.info(message, meta);
}
warn(message, meta) {
logger.warn(message, meta);
}
error(message, meta) {
logger.error(message, meta);
}
logRequest(method, url, headers, body) {
logger.info('API Request', {
method,
url,
headers: this.sanitizeHeaders(headers),
bodySize: body ? JSON.stringify(body).length : 0
});
}
logResponse(statusCode, headers, body) {
const level = statusCode >= 400 ? 'error' : 'info';
logger[level]('API Response', {
statusCode,
headers: headers,
bodySize: body ? JSON.stringify(body).length : 0
});
}
sanitizeHeaders(headers) {
const sanitized = { ...headers };
if (sanitized.Authorization) {
sanitized.Authorization = 'Bearer ***';
}
return sanitized;
}
}
// Use custom logger
const client = new VerbalisAI({
apiKey: 'your-api-key',
logger: new VerbalisAILogger()
});
import { VerbalisAI } from '@verbalisai/sdk';
// Custom retry configuration
const client = new VerbalisAI({
apiKey: 'your-api-key',
// Retry settings
maxRetries: 5,
retryDelay: 1000,
maxRetryDelay: 60000,
retryFactor: 2.0,
jitter: true,
// Custom retry condition
shouldRetry: (error, attempt) => {
// Retry on network errors and 5xx responses
if (error.code === 'NETWORK_ERROR') return true;
if (error.statusCode >= 500) return true;
if (error.statusCode === 429) return true; // Rate limit
// Don't retry client errors (4xx except 429)
if (error.statusCode >= 400 && error.statusCode < 500) return false;
// Retry up to max attempts
return attempt < 5;
},
// Custom retry delay calculation
getRetryDelay: (attempt, error) => {
// Exponential backoff with jitter
const baseDelay = 1000;
const maxDelay = 60000;
let delay = baseDelay * Math.pow(2, attempt);
// Add jitter (random factor)
delay = delay * (0.5 + Math.random() * 0.5);
// Respect rate limit headers
if (error.statusCode === 429 && error.headers['retry-after']) {
const retryAfter = parseInt(error.headers['retry-after']) * 1000;
delay = Math.max(delay, retryAfter);
}
return Math.min(delay, maxDelay);
}
});
// Exponential backoff with circuit breaker
class CircuitBreaker {
constructor(options = {}) {
this.failureThreshold = options.failureThreshold || 5;
this.recoveryTimeout = options.recoveryTimeout || 60000;
this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
this.failureCount = 0;
this.lastFailureTime = null;
}
async execute(fn) {
if (this.state === 'OPEN') {
if (Date.now() - this.lastFailureTime >= this.recoveryTimeout) {
this.state = 'HALF_OPEN';
} else {
throw new Error('Circuit breaker is OPEN');
}
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
onSuccess() {
this.failureCount = 0;
this.state = 'CLOSED';
}
onFailure() {
this.failureCount++;
this.lastFailureTime = Date.now();
if (this.failureCount >= this.failureThreshold) {
this.state = 'OPEN';
}
}
}
const circuitBreaker = new CircuitBreaker({
failureThreshold: 3,
recoveryTimeout: 30000
});
const client = new VerbalisAI({
apiKey: 'your-api-key',
// Use circuit breaker for requests
requestInterceptor: async (config) => {
return circuitBreaker.execute(() => config);
}
});
import https from 'https';
import { VerbalisAI } from '@verbalisai/sdk';
// Custom HTTPS agent with specific settings
const httpsAgent = new https.Agent({
// Connection pooling
keepAlive: true,
keepAliveMsecs: 30000,
maxSockets: 50,
maxFreeSockets: 10,
// Timeouts
timeout: 30000,
// SSL/TLS settings
rejectUnauthorized: true,
secureProtocol: 'TLSv1_2_method'
});
const client = new VerbalisAI({
apiKey: 'your-api-key',
// Custom HTTP agent
httpAgent: httpsAgent,
// Additional HTTP options
httpOptions: {
headers: {
'Connection': 'keep-alive',
'User-Agent': 'MyApp/1.0'
}
}
});
import { HttpsProxyAgent } from 'https-proxy-agent';
import { VerbalisAI } from '@verbalisai/sdk';
// Configure proxy
const proxyAgent = new HttpsProxyAgent('http://proxy.company.com:8080');
const client = new VerbalisAI({
apiKey: 'your-api-key',
httpAgent: proxyAgent,
// Proxy authentication (if required)
proxyAuth: {
username: 'proxy-user',
password: 'proxy-pass'
}
});
import { VerbalisAI } from '@verbalisai/sdk';
// Set default transcription options
const client = new VerbalisAI({
apiKey: 'your-api-key',
// Default transcription settings
transcriptionDefaults: {
model: 'pro',
language: 'en',
diarize: true,
topics: true,
summarization: true,
summaryType: 'bullets',
timestampStyle: 'word',
redactPii: false
}
});
// These defaults will be used if not overridden
const transcription = await client.transcriptions.create({
audioUrl: 'https://example.com/audio.mp3'
// model: 'pro', diarize: true, etc. applied automatically
});
const client = new VerbalisAI({
apiKey: 'your-api-key',
// Default file upload settings
uploadDefaults: {
chunkSize: 10 * 1024 * 1024, // 10MB chunks
timeout: 300000, // 5 minutes
autoDeleteDays: 30,
public: false,
// Default folder structure
folderTemplate: 'uploads/{year}/{month}',
// Default tags
defaultTags: ['uploaded', 'pending-processing']
}
});
import { VerbalisAI } from '@verbalisai/sdk';
// Configure for specific regions
const regions = {
'us-east': 'https://us-east.api.verbalisai.com/api',
'eu-west': 'https://eu-west.api.verbalisai.com/api',
'asia-pacific': 'https://ap.api.verbalisai.com/api'
};
// Initialize client for specific region
const clientUS = new VerbalisAI({
apiKey: 'your-api-key',
baseUrl: regions['us-east']
});
const clientEU = new VerbalisAI({
apiKey: 'your-api-key',
baseUrl: regions['eu-west']
});
// Automatic region selection based on location
async function createRegionalClient(apiKey) {
// Detect user's region (simplified)
const userRegion = await getUserRegion();
const regionEndpoints = {
'US': 'https://us-east.api.verbalisai.com/api',
'EU': 'https://eu-west.api.verbalisai.com/api',
'ASIA': 'https://ap.api.verbalisai.com/api'
};
return new VerbalisAI({
apiKey,
baseUrl: regionEndpoints[userRegion] || regions['us-east']
});
}
async function getUserRegion() {
// Implementation to detect user's region
// Could use IP geolocation, browser locale, etc.
return 'US';
}
const client = new VerbalisAI({
apiKey: 'your-api-key',
baseUrl: 'https://custom.api.endpoint.com/v1',
// Override specific endpoints
endpoints: {
transcription: '/custom/transcribe',
files: '/custom/files',
usage: '/custom/usage'
}
});
import { VerbalisAI } from '@verbalisai/sdk';
// Optimized for high-throughput applications
const client = new VerbalisAI({
apiKey: 'your-api-key',
// HTTP connection settings
httpOptions: {
keepAlive: true,
keepAliveMsecs: 60000,
maxSockets: 100, // Allow many concurrent connections
maxFreeSockets: 20, // Keep connections alive
timeout: 120000 // 2 minutes timeout
},
// Request optimization
maxConcurrentRequests: 50, // Limit concurrent requests
requestQueue: true, // Queue requests when limit reached
// Response optimization
streamResponses: true, // Stream large responses
compressionEnabled: true // Enable gzip compression
});
// Memory-efficient configuration for large file processing
const client = new VerbalisAI({
apiKey: 'your-api-key',
// Streaming settings
streamResponses: true, // Stream large responses
uploadChunkSize: 5 * 1024 * 1024, // Smaller chunks to reduce memory
// Connection limits to prevent memory issues
maxConcurrentRequests: 10,
// Enable automatic cleanup
autoCleanup: true,
cleanupInterval: 300000 // Clean up every 5 minutes
});
// Use with async iteration for memory efficiency
async function processLargeFiles(audioUrls) {
const results = [];
// Process files in batches to manage memory
const batchSize = 5;
for (let i = 0; i < audioUrls.length; i += batchSize) {
const batch = audioUrls.slice(i, i + batchSize);
const batchPromises = batch.map(url =>
client.transcriptions.create({ audioUrl: url })
);
const batchResults = await Promise.all(batchPromises);
results.push(...batchResults);
// Process results immediately to free memory
for (const result of batchResults) {
await processTranscription(result);
}
// Optional: Force garbage collection if available
if (global.gc) {
global.gc();
}
}
return results;
}
async function processTranscription(transcription) {
// Process and save transcription immediately
console.log(`Processed: ${transcription.id}`);
}
import { VerbalisAI, validateConfig } from '@verbalisai/sdk';
async function validateClientConfig() {
const config = {
apiKey: 'your-api-key',
baseUrl: 'https://api.verbalisai.com/api',
timeout: 30000,
maxRetries: 3
};
try {
// Validate configuration before creating client
const validationResult = await validateConfig(config);
if (validationResult.isValid) {
const client = new VerbalisAI(config);
console.log('Configuration is valid');
return client;
} else {
console.error('Configuration errors:', validationResult.errors);
throw new Error('Invalid configuration');
}
} catch (error) {
console.error('Configuration validation failed:', error);
throw error;
}
}
// Usage
try {
const client = await validateClientConfig();
console.log('Client created successfully');
} catch (error) {
console.error('Failed to create client:', error);
}
async function healthCheck() {
const client = new VerbalisAI({ apiKey: 'your-api-key' });
try {
// Test basic connectivity
const health = await client.healthCheck();
console.log(`API Status: ${health.status}`);
console.log(`Response Time: ${health.responseTimeMs}ms`);
console.log(`Region: ${health.region}`);
console.log(`Version: ${health.apiVersion}`);
if (health.status === 'healthy') {
console.log('✅ Client configuration is working correctly');
return true;
} else {
console.log('❌ API health check failed');
return false;
}
} catch (error) {
console.log(`❌ Health check failed: ${error.message}`);
return false;
}
}
// Usage
const isHealthy = await healthCheck();
if (!isHealthy) {
console.log('Consider checking your configuration or API status');
}
import { VerbalisAI } from '@verbalisai/sdk';
class ConfigurationManager {
constructor() {
this.profiles = {
development: {
apiKey: process.env.DEV_API_KEY,
baseUrl: 'https://dev-api.verbalisai.com/api',
timeout: 10000,
maxRetries: 1,
enableLogging: true,
logLevel: 'debug'
},
staging: {
apiKey: process.env.STAGING_API_KEY,
baseUrl: 'https://staging-api.verbalisai.com/api',
timeout: 30000,
maxRetries: 3,
enableLogging: true,
logLevel: 'info'
},
production: {
apiKey: process.env.PROD_API_KEY,
baseUrl: 'https://api.verbalisai.com/api',
timeout: 60000,
maxRetries: 5,
enableLogging: false,
logLevel: 'error'
}
};
}
getClient(profile = 'production') {
const config = this.profiles[profile];
if (!config) {
throw new Error(`Unknown profile: ${profile}`);
}
return new VerbalisAI(config);
}
// Environment-based client creation
getClientForEnvironment() {
const env = process.env.NODE_ENV || 'production';
const profileMap = {
'development': 'development',
'test': 'staging',
'staging': 'staging',
'production': 'production'
};
return this.getClient(profileMap[env] || 'production');
}
}
// Usage
const configManager = new ConfigurationManager();
// Different clients for different environments
const devClient = configManager.getClient('development');
const prodClient = configManager.getClient('production');
// Automatic environment detection
const client = configManager.getClientForEnvironment();
// Browser-specific configuration
const client = new VerbalisAI({
apiKey: 'your-api-key',
// Browser-specific settings
timeout: 120000, // Longer timeout for browser requests
// CORS handling
corsEnabled: true,
// File upload settings for browser
uploadChunkSize: 2 * 1024 * 1024, // Smaller chunks for browser
// Progress tracking
enableProgressTracking: true,
// Browser storage for caching
cacheEnabled: true,
cacheStorage: 'localStorage' // or 'sessionStorage', 'indexedDB'
});
// Service Worker integration
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(() => {
// Configure client to work with service worker
client.configureServiceWorker({
enableBackgroundSync: true,
enableOfflineMode: true
});
});
}
import { VerbalisAIError } from '@verbalisai/sdk';
class CustomErrorHandler {
constructor() {
this.errorCounts = new Map();
}
async handleError(error, context) {
const errorType = error.constructor.name;
this.errorCounts.set(errorType, (this.errorCounts.get(errorType) || 0) + 1);
// Custom error handling logic
if (error.statusCode === 429) {
return await this.handleRateLimit(error, context);
} else if (error.statusCode >= 500) {
return await this.handleServerError(error, context);
} else {
return await this.handleClientError(error, context);
}
}
async handleRateLimit(error, context) {
const retryAfter = error.headers['retry-after'] || 60;
console.log(`Rate limit exceeded. Retry after: ${retryAfter}s`);
return {
retry: true,
delay: retryAfter * 1000
};
}
async handleServerError(error, context) {
console.error(`Server error: ${error.statusCode} - ${error.message}`);
// Log to external service
await this.logToExternalService(error, context);
return {
retry: true,
delay: 5000
};
}
async handleClientError(error, context) {
console.error(`Client error: ${error.statusCode} - ${error.message}`);
return { retry: false };
}
async logToExternalService(error, context) {
// Log to external monitoring service
try {
await fetch('/api/log-error', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
error: error.message,
statusCode: error.statusCode,
context: context,
timestamp: new Date().toISOString()
})
});
} catch (logError) {
console.error('Failed to log error to external service:', logError);
}
}
getErrorStats() {
return Object.fromEntries(this.errorCounts);
}
}
// Use custom error handler
const errorHandler = new CustomErrorHandler();
const client = new VerbalisAI({
apiKey: 'your-api-key',
errorHandler: errorHandler
});
// Get error statistics
setInterval(() => {
const stats = errorHandler.getErrorStats();
console.log('Error statistics:', stats);
}, 60000); // Every minute
Ready to see real-world examples? Check out the Examples guide for practical implementations and use cases with the JavaScript SDK.