'Message is empty.']); exit; } $aiReply = 'Sorry, I could not process your request at the moment.'; $responseSuccess = false; try { $systemPrompt = 'You are a friendly and helpful AI assistant for IBMR Festverse, a college event management platform. Your goal is to answer questions about events, help users discover fests, and provide information about the platform. Keep your answers concise and cheerful.'; // Create the payload for the AI API $payload = [ 'input' => [ ['role' => 'system', 'content' => $systemPrompt], ['role' => 'user', 'content' => $userMessage], ], ]; // Options for the API call $options = [ 'poll_interval' => 5, // seconds 'poll_timeout' => 120 // seconds ]; // Call the AI service $resp = LocalAIApi::createResponse($payload, $options); if (!empty($resp['success'])) { $text = LocalAIApi::extractText($resp); if ($text !== '') { $aiReply = $text; $responseSuccess = true; } else { // Handle cases where AI gives a non-text response or empty text $aiReply = 'I received a response, but it was empty. Can you try rephrasing?'; } } else { error_log('AI API Error: ' . ($resp['error'] ?? 'Unknown error')); $aiReply = 'There was an issue connecting to the AI service. Please try again later.'; } } catch (Exception $e) { error_log('AI Chat Exception: ' . $e->getMessage()); $aiReply = 'A server error occurred. We are looking into it.'; } if ($responseSuccess) { echo json_encode(['reply' => $aiReply]); } else { // In case of an error, we still return a JSON response with a user-friendly message // The specific error is logged on the server for debugging echo json_encode(['reply' => $aiReply]); }