ChatGPT AI 网站源码示例 - 使用 JavaScript 实现聊天机器人
以下是一个简单的网站源码示例,用于调用 ChatGPT AI 模型,实现一个简单的聊天机器人:
- HTML 文件 (index.html):
<!DOCTYPE html>
<html>
<head>
<title>ChatGPT AI Demo</title>
</head>
<body>
<h1>ChatGPT AI Demo</h1>
<div id='chat-container'>
<div id='chat-log'></div>
<input type='text' id='user-input' placeholder='输入消息...' />
<button id='send-button' onclick='sendMessage()'>发送</button>
</div>
<script src='https://code.jquery.com/jquery-3.6.0.min.js'></script>
<script src='script.js'></script>
</body>
</html>
- JavaScript 文件 (script.js):
$(document).ready(function() {
// ChatGPT API URL
const apiUrl = 'https://api.openai.com/v1/engines/davinci-codex/completions';
// 替换为您的 OpenAI API 密钥
const apiKey = 'YOUR_API_KEY';
// 聊天记录容器
const chatLog = $('#chat-log');
// 向 ChatGPT 发送用户消息
function sendMessage() {
const userInput = $('#user-input').val();
if (userInput.trim() === '') {
return;
}
// 将用户消息添加到聊天记录
chatLog.append('<div class='user-message'>' + userInput + '</div>');
// 清空用户输入框
$('#user-input').val('');
// 调用 ChatGPT API
$.ajax({
url: apiUrl,
type: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + apiKey
},
data: JSON.stringify({
'prompt': userInput,
'max_tokens': 50 // 根据需要调整
}),
success: function(response) {
const chatGptResponse = response.choices[0].text.trim();
// 将 ChatGPT 响应添加到聊天记录
chatLog.append('<div class='chatgpt-message'>' + chatGptResponse + '</div>');
// 滚动到聊天记录底部
chatLog.scrollTop(chatLog[0].scrollHeight);
},
error: function() {
alert('Error calling the ChatGPT API.');
}
});
}
// 注册回车键按下事件
$('#user-input').keypress(function(event) {
if (event.which === 13) {
sendMessage();
}
});
});
请注意,此源码示例仅提供了一个基本的前端实现,您需要将其中的 YOUR_API_KEY 替换为您自己的 OpenAI API 密钥,并确保已在 OpenAI 平台上创建了 ChatGPT AI 模型。此外,还应根据需要进行样式和布局的自定义。
原文地址: https://www.cveoy.top/t/topic/qqAq 著作权归作者所有。请勿转载和采集!