All files / shared/utils/src/api-clients tavus-cost-controller.ts

0% Statements 0/68
0% Branches 0/26
0% Functions 0/19
0% Lines 0/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * 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<TavusCostConfig>) {
    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;
    
    Iif (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 {
    Iif (!this.shouldApplyCostControls()) return;
 
    console.log(`[TavusCostController] Starting conversation monitoring for ${conversationId}`);
    
    this.usageStats.conversationStartTime = Date.now();
    
    // Set up auto-end timer
    Iif (this.config.autoEndConversations) {
      this.conversationTimer = setTimeout(() => {
        this.autoEndConversation(conversationId);
      }, this.config.maxConversationDuration * 1000);
    }
  }
 
  /**
   * Stop monitoring a conversation
   */
  public stopConversationMonitoring(): void {
    Iif (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 {
    Iif (!this.shouldApplyCostControls()) return true;
 
    const now = Date.now();
    
    // Rate limiting
    Iif (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
    Iif (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<string, number> = {
      '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 {
    Iif (!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<TavusCostConfig>): 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();