38808-vm/api/chat.php
2026-03-01 02:53:25 +00:00

69 lines
3.0 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../ai/LocalAIApi.php';
$input = json_decode(file_get_contents('php://input'), true);
$message = $input['message'] ?? '';
if (empty($message)) {
echo json_encode(['reply' => "لم أفهم ذلك. هل يمكنك التكرار؟"]);
exit;
}
try {
// 1. Fetch Knowledge Base (FAQs)
$stmt = db()->query("SELECT keywords, answer FROM faqs");
$faqs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$knowledgeBase = "إليك قاعدة المعرفة لهذا الموقع:\n\n";
foreach ($faqs as $faq) {
$knowledgeBase .= "س: " . $faq['keywords'] . "\nج: " . $faq['answer'] . "\n---\n";
}
// 2. Construct Prompt for AI
$systemPrompt = "أنت مساعد ذكاء اصطناعي مفيد وودود لهذا الموقع. " .
"استخدم قاعدة المعرفة المقدمة للإجابة على أسئلة المستخدمين بدقة. " .
"إذا كانت الإجابة موجودة في قاعدة المعرفة، فقم بصياغتها بشكل طبيعي. " .
"إذا لم تكن الإجابة في قاعدة المعرفة، فاستخدم معرفتك العامة للمساعدة، " .
"ولكن اذكر بأدب أنك ليس لديك معلومات محددة حول ذلك إذا كان يبدو سؤالاً خاصاً بالموقع. " .
"اجعل الإجابات موجزة واحترافية وباللغة العربية.\n\n" .
$knowledgeBase;
// 3. Call AI API
$response = LocalAIApi::createResponse([
'model' => 'gpt-4o-mini',
'input' => [
['role' => 'system', 'content' => $systemPrompt],
['role' => 'user', 'content' => $message],
]
]);
if (!empty($response['success'])) {
$text = LocalAIApi::extractText($response);
if ($text === '') {
$decoded = LocalAIApi::decodeJsonFromResponse($response);
$text = $decoded ? json_encode($decoded, JSON_UNESCAPED_UNICODE) : (string)($response['data'] ?? '');
}
$aiReply = $text;
// 4. Save to Database
try {
$stmt = db()->prepare("INSERT INTO messages (user_message, ai_response) VALUES (?, ?)");
$stmt->execute([$message, $aiReply]);
} catch (Exception $e) {
error_log("DB Save Error: " . $e->getMessage());
// Continue even if save fails, so the user still gets a reply
}
echo json_encode(['reply' => $aiReply]);
} else {
// Fallback if AI fails
error_log("AI Error: " . ($response['error'] ?? 'Unknown'));
echo json_encode(['reply' => "أواجه مشكلة في الاتصال بذكائي الآن. يرجى المحاولة مرة أخرى لاحقاً."]);
}
} catch (Exception $e) {
error_log("Chat Error: " . $e->getMessage());
echo json_encode(['reply' => "حدث خطأ داخلي."]);
}