写一个chatgpt的聊天PHP单页!
当使用OpenAI ChatGPT API时,可以使用以下代码编写一个聊天的PHP单页应用:
<!DOCTYPE html>
<html>
<head>
<title>ChatGPT Chatbot</title>
<style>
body {
font-family: Arial, sans-serif;
}
.chat-container {
width: 400px;
margin: 0 auto;
border: 1px solid #ccc;
padding: 20px;
background-color: #f9f9f9;
}
.user-message {
background-color: #e2f0cb;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
.bot-message {
background-color: #f0f0f0;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="chat-container">
<h1>ChatGPT Chatbot</h1>
<div id="chat-log"></div>
<form id="chat-form" method="post">
<input type="text" id="user-input" placeholder="Type your message..." autocomplete="off" />
<button type="submit">Send</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#chat-form').submit(function(e) {
e.preventDefault();
var userInput = $('#user-input').val();
if (userInput.trim() !== '') {
addUserMessage(userInput);
$('#user-input').val('');
sendChatMessage(userInput);
}
});
function addUserMessage(message) {
var html = '<div class="user-message">' + message + '</div>';
$('#chat-log').append(html);
$('#chat-log').scrollTop($('#chat-log')[0].scrollHeight);
}
function addBotMessage(message) {
var html = '<div class="bot-message">' + message + '</div>';
$('#chat-log').append(html);
$('#chat-log').scrollTop($('#chat-log')[0].scrollHeight);
}
function sendChatMessage(message) {
$.ajax({
url: 'https://api.openai.com/v1/chat/completions',
type: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
data: JSON.stringify({
'model': 'gpt-3.5-turbo',
'messages': [{'role': 'system', 'content': 'You are a helpful assistant.'}, {'role': 'user', 'content': message}]
}),
success: function(data) {
var botMessage = data.choices[0].message.content;
addBotMessage(botMessage);
}
});
}
});
</script>
</body>
</html>
请注意将代码中的YOUR_API_KEY替换为您的OpenAI API密钥。此示例使用jQuery库来处理表单提交和AJAX请求。页面包含一个聊天容器,用户可以在输入框中输入消息并通过点击发送按钮发送给ChatGPT模型。模型的响应将以用户和机器人的消息形式显示在聊天容器中。
在使用此代码之前,请确保已经了解如何使用OpenAI ChatGPT API,并已在OpenAI平台上创建了一个ChatGPT模型
原文地址: https://www.cveoy.top/t/topic/iAJT 著作权归作者所有。请勿转载和采集!