🤖 AI-Чат (Задайте вопрос)
Вы: ${message}
`;
input.value = "";
// Отправляем на сервер PHP
fetch("/chat.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message })
})
.then(response => response.json())
.then(data => {
chatMessages.innerHTML += `Бот: ${data.reply}
`;
chatMessages.scrollTop = chatMessages.scrollHeight;
});
});
// Backend: chat.php - обработка запросов к OpenAI API
// Размести этот файл в корне OpenCart
"Ошибка: пустое сообщение."]);
exit;
}
$api_key = "ТВОЙ_API_КЛЮЧ_OPENAI";
$url = "https://api.openai.com/v1/chat/completions";
$data = [
"model" => "gpt-4",
"messages" => [["role" => "user", "content" => $message]],
"temperature" => 0.7
];
$options = [
"http" => [
"header" => "Content-Type: application/json\r\n" .
"Authorization: Bearer $api_key\r\n",
"method" => "POST",
"content" => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$result = json_decode($response, true);
$reply = $result['choices'][0]['message']['content'] ?? "Ошибка получения ответа.";
echo json_encode(["reply" => $reply]);
?>
Комментариев нет:
Отправить комментарий