/** * Tavus Generate Deck Tool Handler * * API endpoint that receives Tavus tool call parameters directly * and transforms them to call the slidev-generate endpoint. * * Path: POST /api/tavus/generate-deck * * Updated: 2025-10-10 - Made conversation_id optional */ export const config = { name: 'TavusGenerateDeckTool', type: 'api', path: '/api/tavus/generate-deck', method: 'POST', description: 'Handle Tavus generate_custom_deck tool calls', emits: ['tavus.deck.requested'] }; interface TavusToolInput { company_name: string; pain_points: string[]; interested_features: string[]; industry?: string; team_size?: string; budget_range?: string; conversation_id: string; // Added by frontend from app-message event } interface TavusToolOutput { deckId: string; deckUrl: string; message: string; } export const handler = async (req: MotiaRequest, { emit }: MotiaContext) => { try { console.log('[TavusGenerateDeckTool] Raw request:', { hasBody: !!req.body, bodyType: typeof req.body, bodyKeys: req.body ? Object.keys(req.body) : [], fullBody: req.body }); const input: TavusToolInput = req.body; console.log('[TavusGenerateDeckTool] Received tool call:', { company_name: input.company_name, conversation_id: input.conversation_id, pain_points_count: input.pain_points?.length || 0, features_count: input.interested_features?.length || 0 }); // Validate required inputs from Tavus if (!input.company_name || !input.pain_points || !input.interested_features) { return { status: 400, body: { error: 'Validation failed', details: 'Missing required Tavus tool parameters: company_name, pain_points, interested_features' } }; } // Generate conversation_id if not provided // Frontend adds this from app-message event, but if called directly, generate one const conversationId = input.conversation_id || `tavus-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; if (!input.conversation_id) { console.log('[TavusGenerateDeckTool] No conversation_id provided, generated:', conversationId); } // Step 1: Ensure session exists in Supabase const supabaseUrl = process.env.SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_KEY; if (!supabaseUrl || !supabaseServiceKey) { throw new Error('SUPABASE_URL or SUPABASE_SERVICE_KEY not configured'); } console.log('[TavusGenerateDeckTool] Creating/verifying session:', conversationId); // Try to create session (will fail if exists, which is fine) const sessionData = { id: conversationId, tavus_conversation_id: conversationId, status: 'discovery_complete' }; const sessionResponse = await fetch( `${supabaseUrl}/rest/v1/conversation_sessions`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'apikey': supabaseServiceKey, 'Authorization': `Bearer ${supabaseServiceKey}`, 'Prefer': 'return=representation' }, body: JSON.stringify(sessionData) } ); if (!sessionResponse.ok) { const errorText = await sessionResponse.text(); // If duplicate key, session already exists - that's fine if (!errorText.includes('duplicate key')) { console.warn('[TavusGenerateDeckTool] Session creation warning:', errorText); } else { console.log('[TavusGenerateDeckTool] Session already exists'); } } else { console.log('[TavusGenerateDeckTool] Session created successfully'); } // Step 2: Transform Tavus parameters to Slidev format const slideData = { company: input.company_name, tagline: `Solutions for ${input.company_name}`, description: input.pain_points.length > 0 ? `We help with: ${input.pain_points.join(', ')}` : 'Custom solutions tailored to your needs', industry: input.industry || 'Business', features: input.interested_features.join(', ') }; const slidevInput = { sessionId: conversationId, templateId: 'default', data: slideData }; console.log('[TavusGenerateDeckTool] Transformed to Slidev format:', { sessionId: slidevInput.sessionId, templateId: slidevInput.templateId, company: slideData.company }); // Step 3: Call the existing slidev-generate endpoint internally // We'll use the same base URL as the current request const baseUrl = process.env.MOTIA_API_URL || 'https://slide-system-production-5813.up.railway.app'; const slidevUrl = `${baseUrl}/api/slidev/generate`; console.log('[TavusGenerateDeckTool] Calling slidev-generate at:', slidevUrl); const slidevResponse = await fetch(slidevUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(slidevInput) }); if (!slidevResponse.ok) { const errorText = await slidevResponse.text(); console.error('[TavusGenerateDeckTool] Slidev generation failed:', errorText); throw new Error(`Slidev generation failed: ${errorText}`); } const slidevResult = await slidevResponse.json(); console.log('[TavusGenerateDeckTool] Deck generated successfully:', { deckId: slidevResult.deckId, deckUrl: slidevResult.deckUrl }); const output: TavusToolOutput = { deckId: slidevResult.deckId, deckUrl: slidevResult.deckUrl, message: `Deck generated for ${input.company_name}` }; // Emit event for tracking emit({ topic: 'tavus.deck.requested', data: { conversation_id: conversationId, company_name: input.company_name, deck_id: output.deckId, deck_url: output.deckUrl } }); return { status: 200, body: output }; } catch (error: unknown) { console.error('[TavusGenerateDeckTool] Error:', error); return { status: 500, body: { error: 'Failed to generate deck from Tavus tool call', details: error.message } }; } };