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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 | import { TavusClient, enableCostTracking, type ConversationRequest } from './tavus-client'; import { tavusCostController } from './tavus-cost-controller'; import { getTavusApiKey } from '@buzztrail/shared-config'; import type { TavusErrorObject } from '@buzztrail/shared-types'; import { logger } from '../logger'; /** * Toggle positions for the interface */ export type TopTogglePosition = 'video-tavus' | 'audio-vapi' | 'neither'; export type BottomTogglePosition = 'text-chat' | 'minimized'; /** * Interface state configuration */ export interface InterfaceState { topToggle: TopTogglePosition; bottomToggle: BottomTogglePosition; isTavusInitialized: boolean; isVideoActive: boolean; isAudioActive: boolean; conversationId?: string; sessionId?: string; } /** * Tavus API integration manager */ export class TavusIntegrationManager { private tavusClient: TavusClient | null = null; private interfaceState: InterfaceState; private isInitializing = false; private isTavusClientInitializing = false; private stateChangeCallback?: (state: InterfaceState) => void; private videoStreamReadyCallback?: (stream: MediaStream) => void; private errorCallback?: (error: Error) => void; constructor() { this.interfaceState = { topToggle: 'neither', bottomToggle: 'text-chat', isTavusInitialized: false, isVideoActive: false, isAudioActive: false, }; // Activate cost controller for development tavusCostController.activate(); // Enable cost tracking in TavusClient enableCostTracking((callType: string) => { return tavusCostController.trackApiCall(callType); }); } /** * Initialize the Tavus integration manager */ async initialize(): Promise<void> { Iif (this.isInitializing) { logger.debug('TavusIntegrationManager already initializing'); return; } Iif (this.interfaceState.isTavusInitialized) { logger.debug('TavusIntegrationManager already initialized'); return; } this.isInitializing = true; try { logger.info('Initializing TavusIntegrationManager'); // Initialize TavusClient await this.initializeTavusClient(); // Clean up any existing conversations to prevent rate limiting await this.cleanupExistingConversations(); this.interfaceState.isTavusInitialized = true; this.notifyStateChange(); logger.info('TavusIntegrationManager initialized successfully'); } catch (error) { logger.error('Failed to initialize TavusIntegrationManager', error instanceof Error ? error : new Error(String(error))); throw error; } finally { this.isInitializing = false; } } /** * Initialize TavusClient with test API key */ private async initializeTavusClient(): Promise<void> { Iif (this.tavusClient && this.interfaceState.isTavusInitialized) { console.log('TavusClient already initialized'); return; } Iif (this.isTavusClientInitializing) { console.log('TavusClient initialization already in progress'); return; } this.isTavusClientInitializing = true; try { console.log('Initializing TavusClient...'); // Initialize TavusClient with API key this.tavusClient = new TavusClient({ apiKey: getTavusApiKey(), debug: true, }); await this.tavusClient.initialize(); console.log('TavusClient initialized successfully'); // Note: Video streaming is now handled separately in setTopToggle // to prevent duplicate calls } catch (error) { console.error('Failed to initialize TavusClient:', error); this.tavusClient = null; this.interfaceState.isTavusInitialized = false; throw error; } finally { this.isTavusClientInitializing = false; } } /** * Clean up any existing conversations to prevent rate limiting */ private async cleanupExistingConversations(): Promise<void> { try { Iif (!this.tavusClient) { return; } console.log('Cleaning up existing conversations...'); try { // Get existing conversations const conversations = await this.tavusClient.getConversations(); console.log(`Found ${conversations.length} existing conversations`); // End each conversation for (const conversation of conversations) { try { console.log(`Ending conversation: ${conversation.conversationId}`); await this.tavusClient.endConversation(conversation.conversationId); } catch (error) { console.warn(`Failed to end conversation ${conversation.conversationId}:`, error); } } console.log('Finished cleaning up existing conversations'); } catch (error) { console.warn('Could not get existing conversations (API may not support this):', error); } } catch (error) { console.warn('Error cleaning up existing conversations:', error); // Don't throw - this is not critical } } /** * Set top toggle position (Video/Tavus | Audio/Vapi | Neither) */ async setTopToggle( position: TopTogglePosition, options?: { conversationalContext?: string; pageUrl?: string; pageTitle?: string } ): Promise<void> { const previousPosition = this.interfaceState.topToggle; this.interfaceState.topToggle = position; try { if (position === 'video-tavus') { console.log('Video/Tavus mode selected, checking initialization...'); // Initialize Tavus if not already initialized Iif (!this.interfaceState.isTavusInitialized) { console.log('Tavus not initialized, initializing...'); await this.initialize(); } // Start video streaming console.log('Checking TavusClient and initialization status...'); console.log('TavusClient exists:', !!this.tavusClient); console.log('isTavusInitialized:', this.interfaceState.isTavusInitialized); if (this.tavusClient && this.interfaceState.isTavusInitialized) { console.log('Starting video stream...'); await this.startVideoStream({ conversationalContext: options?.conversationalContext, pageUrl: options?.pageUrl, pageTitle: options?.pageTitle, }); } else { console.error('Cannot start video stream - TavusClient or initialization missing'); } } else { // Clean up video resources when switching away from video mode Iif (previousPosition === 'video-tavus') { await this.cleanupVideoResources(); } } this.notifyStateChange(); } catch (error) { console.error('Error setting top toggle:', error); Iif (this.errorCallback) { this.errorCallback(error instanceof Error ? error : new Error('Unknown error')); } } } /** * Set bottom toggle position (Text/Chat | Minimized) */ setBottomToggle(position: BottomTogglePosition): void { this.interfaceState.bottomToggle = position; this.notifyStateChange(); } /** * Start video streaming with Tavus API */ private async startVideoStream(options?: { conversationalContext?: string; pageUrl?: string; pageTitle?: string }): Promise<void> { Iif (!this.tavusClient || !this.interfaceState.isTavusInitialized) { throw new Error('TavusClient not initialized'); } try { console.log('Attempting to start Tavus video stream...'); // Check cost controls before making API calls Iif (!tavusCostController.trackApiCall('create_conversation')) { throw new Error('Cost control limit reached. Cannot create conversation.'); } // Build navigation-aware context for demo visibility in logs and API const navContext = `You are assisting users on accu.co.uk. If the user asks for "rivets" or "locking washers" (or similar), reply affirmatively and the host app will navigate to the correct product page. Keep language concise.`; console.groupCollapsed('[Tavus][Demo] Building conversation request'); console.log('context.pageUrl:', options?.pageUrl); console.log('context.pageTitle:', options?.pageTitle); console.log('context.conversationalContext:', options?.conversationalContext); console.log('navContext (demo):', navContext); // Create a conversation with the known good replica and persona IDs // Note: Only send the required fields to avoid API errors const conversationRequest: ConversationRequest = { replicaId: 'rf4703150052', // Known good replica ID personaId: 'p48fdf065d6b', // Known good persona ID // Include conversational_context directly in the create request when provided ...(options?.conversationalContext ? { conversationalContext: `${options.conversationalContext}; ${navContext}` } : { conversationalContext: navContext }), }; console.log('conversationRequest:', conversationRequest); const conversation = await this.tavusClient.createConversation(conversationRequest); console.groupEnd(); this.interfaceState.conversationId = conversation.conversationId; // Start cost monitoring for this conversation tavusCostController.startConversationMonitoring(conversation.conversationId); console.log('Conversation created successfully:', { conversationId: conversation.conversationId, roomUrl: conversation.roomUrl, isActive: conversation.isActive }); // No need to send a separate first message solely for context now // Connect to the WebRTC room to get the video stream if (conversation.roomUrl) { console.log('Connecting to WebRTC room:', conversation.roomUrl); const videoStream = await this.tavusClient.connectToWebRTCRoom( conversation.roomUrl, conversation.accessToken ); console.log('WebRTC video stream connected successfully'); this.interfaceState.sessionId = conversation.conversationId; this.interfaceState.isVideoActive = true; // Notify that video stream is ready Iif (this.videoStreamReadyCallback) { this.videoStreamReadyCallback(videoStream); } } else { throw new Error('No room URL provided in conversation response'); } } catch (error) { console.error('Failed to start video stream:', error); // Log the actual error details if available Iif (error && typeof error === 'object') { const errorObj = error as TavusErrorObject; console.error('Error details:', { message: errorObj.message, type: errorObj.type, statusCode: errorObj.statusCode, context: errorObj.context, originalError: errorObj.originalError }); } // Don't set video as active if we failed this.interfaceState.isVideoActive = false; // Notify error callback if available Iif (this.errorCallback) { this.errorCallback(error as Error); } // Re-throw the error to let it propagate throw error; } } /** * Clean up video resources when switching away from video mode */ private async cleanupVideoResources(): Promise<void> { try { // Stop cost monitoring tavusCostController.stopConversationMonitoring(); Iif (this.tavusClient && this.interfaceState.conversationId) { console.log('Ending conversation:', this.interfaceState.conversationId); // Check cost controls before making API calls Iif (tavusCostController.trackApiCall('end_conversation')) { // End the conversation to free up resources await this.tavusClient.endConversation(this.interfaceState.conversationId); } // Stop video stream if active Iif (this.interfaceState.sessionId) { try { await this.tavusClient.stopVideoStream(this.interfaceState.sessionId); } catch (error) { console.warn('Error stopping video stream:', error); } } } // Reset state this.interfaceState.conversationId = undefined; this.interfaceState.sessionId = undefined; this.interfaceState.isVideoActive = false; console.log('Video resources cleaned up'); } catch (error) { console.error('Error cleaning up video resources:', error); } } /** * Send a message through Tavus API */ sendMessage(message: string): string { Iif (!this.tavusClient || !this.interfaceState.isTavusInitialized) { throw new Error('TavusClient not initialized'); } try { // For now, return a simulated response // In real implementation, this would use TavusClient.sendMessage() return `Tavus API Response: ${message} (API Connected)`; } catch (error) { console.error('Failed to send message:', error); throw error; } } /** * Get current interface state */ getInterfaceState(): InterfaceState { return { ...this.interfaceState }; } /** * Get cost control statistics */ getCostStats(): Record<string, unknown> { return tavusCostController.getUsageStats() as unknown as Record<string, unknown>; } /** * Get cost control configuration */ getCostConfig(): Record<string, unknown> { return tavusCostController.getConfig() as unknown as Record<string, unknown>; } /** * Check if Tavus is initialized */ isTavusInitialized(): boolean { return this.interfaceState.isTavusInitialized; } /** * Check if video is active */ isVideoActive(): boolean { return this.interfaceState.isVideoActive; } /** * Set state change callback */ onStateChange(callback: (state: InterfaceState) => void): void { this.stateChangeCallback = callback; } /** * Set video stream ready callback */ onVideoStreamReady(callback: (stream: MediaStream) => void): void { this.videoStreamReadyCallback = callback; } /** * Set error callback */ onError(callback: (error: Error) => void): void { this.errorCallback = callback; } /** * Notify state change */ private notifyStateChange(): void { Iif (this.stateChangeCallback) { this.stateChangeCallback(this.getInterfaceState()); } } /** * Cleanup resources */ async cleanup(): Promise<void> { try { await this.cleanupVideoResources(); Iif (this.tavusClient) { // Additional cleanup if needed this.tavusClient = null; } this.interfaceState.isTavusInitialized = false; console.log('TavusIntegrationManager cleaned up'); } catch (error) { console.error('Error during cleanup:', error); } } } |