/** * TavusCostController - Manages cost controls for Tavus API usage during development * Prevents excessive credit consumption during testing and development * * This is the shared version that integrates with the existing TavusClient cost tracking system */ export interface TavusCostConfig { isDevelopmentMode: boolean; maxConversationDuration: number; // seconds autoEndConversations: boolean; usageLimit: number; // max API calls per session rateLimitDelay: number; // milliseconds between API calls enableMockMode: boolean; lowCreditThreshold: number; // percentage } export interface TavusUsageStats { totalApiCalls: number; currentSessionCalls: number; estimatedCreditsUsed: number; lastCallTimestamp: number; conversationStartTime?: number; } export class TavusCostController { private config: TavusCostConfig; private usageStats: TavusUsageStats; private conversationTimer?: NodeJS.Timeout; private isActive = false; constructor(config?: Partial) { this.config = { isDevelopmentMode: this.detectDevelopmentMode(), maxConversationDuration: 30, // 30 seconds for testing autoEndConversations: true, usageLimit: 10, rateLimitDelay: 1000, // 1 second between calls enableMockMode: false, lowCreditThreshold: 20, // 20% remaining credits ...config }; this.usageStats = { totalApiCalls: 0, currentSessionCalls: 0, estimatedCreditsUsed: 0, lastCallTimestamp: 0 }; } /** * Detect if we're in development mode */ private detectDevelopmentMode(): boolean { // Check for development environment indicators const isNodeEnv = process.env.NODE_ENV === 'development'; const isTavusDev = process.env.TAVUS_DEV_MODE === 'true'; // Only check window.location if we're in a browser environment let isLocalhost = false; let isDevHostname = false; if (typeof window !== 'undefined' && window.location) { isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'; isDevHostname = window.location.hostname.includes('dev') || window.location.hostname.includes('test'); } return isNodeEnv || isTavusDev || isLocalhost || isDevHostname; } /** * Check if cost controls should be active */ public shouldApplyCostControls(): boolean { return this.config.isDevelopmentMode && this.isActive; } /** * Start monitoring a conversation */ public startConversationMonitoring(conversationId: string): void { if (!this.shouldApplyCostControls()) return; console.log(`[TavusCostController] Starting conversation monitoring for ${conversationId}`); this.usageStats.conversationStartTime = Date.now(); // Set up auto-end timer if (this.config.autoEndConversations) { this.conversationTimer = setTimeout(() => { this.autoEndConversation(conversationId); }, this.config.maxConversationDuration * 1000); } } /** * Stop monitoring a conversation */ public stopConversationMonitoring(): void { if (this.conversationTimer) { clearTimeout(this.conversationTimer); this.conversationTimer = undefined; } this.usageStats.conversationStartTime = undefined; console.log('[TavusCostController] Stopped conversation monitoring'); } /** * Auto-end conversation to prevent ongoing billing */ private autoEndConversation(conversationId: string): void { console.log(`[TavusCostController] Auto-ending conversation ${conversationId} after ${this.config.maxConversationDuration}s`); try { // This would call the Tavus API to end the conversation // For now, we'll just log it console.log(`[TavusCostController] Would end conversation ${conversationId} via API`); // Reset session stats this.usageStats.currentSessionCalls = 0; } catch (error) { console.error('[TavusCostController] Failed to auto-end conversation:', error); } } /** * Track an API call and check limits */ public trackApiCall(callType: string): boolean { if (!this.shouldApplyCostControls()) return true; const now = Date.now(); // Rate limiting if (now - this.usageStats.lastCallTimestamp < this.config.rateLimitDelay) { console.warn(`[TavusCostController] Rate limit exceeded. Waiting ${this.config.rateLimitDelay}ms between calls`); return false; } // Usage limit check if (this.usageStats.currentSessionCalls >= this.config.usageLimit) { console.warn(`[TavusCostController] Usage limit reached (${this.config.usageLimit} calls). Stopping API calls.`); return false; } // Update stats this.usageStats.totalApiCalls++; this.usageStats.currentSessionCalls++; this.usageStats.lastCallTimestamp = now; this.usageStats.estimatedCreditsUsed += this.estimateCreditsForCall(callType); console.log(`[TavusCostController] API call tracked: ${callType}. Session calls: ${this.usageStats.currentSessionCalls}/${this.config.usageLimit}`); return true; } /** * Estimate credits used for different API call types */ private estimateCreditsForCall(callType: string): number { const creditEstimates: Record = { 'create_conversation': 1, 'get_conversation': 0.1, 'end_conversation': 0.1, 'video_stream': 0.5, // per minute 'audio_stream': 0.3, // per minute 'default': 0.1 }; return creditEstimates[callType] || creditEstimates.default; } /** * Get current usage statistics */ public getUsageStats(): TavusUsageStats { return { ...this.usageStats }; } /** * Check if we should warn about low credits */ public shouldWarnLowCredits(remainingCredits: number, totalCredits: number): boolean { if (!this.shouldApplyCostControls()) return false; const percentageRemaining = (remainingCredits / totalCredits) * 100; return percentageRemaining <= this.config.lowCreditThreshold; } /** * Get warning message for low credits */ public getLowCreditWarning(remainingCredits: number, totalCredits: number): string { const percentageRemaining = (remainingCredits / totalCredits) * 100; return `⚠️ Low Tavus credits: ${remainingCredits}/${totalCredits} (${percentageRemaining.toFixed(1)}% remaining). Consider adding more credits for testing.`; } /** * Enable or disable cost controls */ public setDevelopmentMode(enabled: boolean): void { this.config.isDevelopmentMode = enabled; console.log(`[TavusCostController] Development mode ${enabled ? 'enabled' : 'disabled'}`); } /** * Update configuration */ public updateConfig(newConfig: Partial): void { this.config = { ...this.config, ...newConfig }; console.log('[TavusCostController] Configuration updated:', this.config); } /** * Reset usage statistics */ public resetUsageStats(): void { this.usageStats = { totalApiCalls: 0, currentSessionCalls: 0, estimatedCreditsUsed: 0, lastCallTimestamp: 0 }; console.log('[TavusCostController] Usage statistics reset'); } /** * Get current configuration */ public getConfig(): TavusCostConfig { return { ...this.config }; } /** * Check if mock mode is enabled */ public isMockModeEnabled(): boolean { return this.shouldApplyCostControls() && this.config.enableMockMode; } /** * Activate the cost controller */ public activate(): void { this.isActive = true; console.log('[TavusCostController] Activated'); } /** * Deactivate the cost controller */ public deactivate(): void { this.isActive = false; this.stopConversationMonitoring(); console.log('[TavusCostController] Deactivated'); } } // Export singleton instance export const tavusCostController = new TavusCostController();