Hướng dẫn tạo web chat GPT-3 bằng HTML nâng cao
Đây là một ví dụ về cách tạo một web chat sử dụng GPT-3 và HTML:
<!DOCTYPE html>
<html>
<head>
<title>Web Chat GPT-3</title>
<script src='https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js'></script>
<script src='https://code.jquery.com/jquery-3.6.0.min.js'></script>
</head>
<body>
<h1>Web Chat GPT-3</h1>
<div id='chat-container'>
<div id='chat-log'></div>
<div id='input-container'>
<input type='text' id='user-input' placeholder='Type your message...' />
<button id='send-button'>Send</button>
</div>
</div>
<script>
// Function to send user message to GPT-3 and get response
function sendMessage(message) {
axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
prompt: message,
max_tokens: 50,
temperature: 0.6
}, {
headers: {
'Authorization': 'Bearer YOUR_GPT3_API_KEY',
'Content-Type': 'application/json',
}
})
.then(function (response) {
var botReply = response.data.choices[0].text.trim();
appendMessage('Bot', botReply);
})
.catch(function (error) {
console.log(error);
});
}
// Function to append a new message to the chat log
function appendMessage(sender, message) {
var chatLog = $('#chat-log');
var messageElement = $('<div></div>').addClass('message');
var senderElement = $('<div></div>').addClass('sender').text(sender + ':');
var messageContent = $('<div></div>').addClass('message-content').text(message);
messageElement.append(senderElement);
messageElement.append(messageContent);
chatLog.append(messageElement);
chatLog.scrollTop(chatLog[0].scrollHeight);
}
// Function to handle user input and send messages
function handleUserInput() {
var userInput = $('#user-input').val();
if (userInput.trim() !== '') {
appendMessage('User', userInput);
sendMessage(userInput);
$('#user-input').val('');
}
}
// Event listener for send button
$('#send-button').click(function() {
handleUserInput();
});
// Event listener for Enter key press
$('#user-input').keypress(function(event) {
if (event.which == 13) {
handleUserInput();
}
});
</script>
</body>
</html>
Vui lòng thay đổi YOUR_GPT3_API_KEY bằng khóa API của bạn từ OpenAI. Đồng thời, bạn cần có kết nối Internet để tải tệp JavaScript từ các nguồn bên ngoài (axios và jQuery).
Đoạn mã trên tạo ra một giao diện web đơn giản với một hộp chat và một nút gửi. Khi người dùng nhập một tin nhắn và nhấn nút gửi hoặc nhấn Enter, tin nhắn sẽ được gửi đến GPT-3 thông qua API và phản hồi của bot sẽ được hiển thị lại trong hộp chat.
原文地址: https://www.cveoy.top/t/topic/o7i7 著作权归作者所有。请勿转载和采集!