68 lines
2.2 KiB
PHP
68 lines
2.2 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
ini_set('display_errors', '0');
|
|
error_reporting(E_ALL);
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
require_once __DIR__ . '/../ai/LocalAIApi.php';
|
|
|
|
// Get the user's message from the POST request
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
$userMessage = $input['message'] ?? '';
|
|
|
|
if (empty($userMessage)) {
|
|
echo json_encode(['error' => '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]);
|
|
}
|