以下是一个简单的前端代码示例,可以根据自己的需求进行调整:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Chat with ChatGPT</title>
	<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
	<h1>Chat with ChatGPT</h1>
	<label for="message">Your message:</label>
	<input type="text" id="message">
	<button onclick="sendMessage()">Send</button>
	<div id="chatbox"></div>
	<script>
		const apiKey = 'YOUR_API_KEY'; // 替换为 ChatGPT 的 API 密钥
		const chatbox = document.getElementById("chatbox");
		const messageInput = document.getElementById("message");

		function sendMessage() {
			const message = messageInput.value;
			if (message) {
				axios.post('https://api.openai.com/v1/engine/turing/completions/chat', {
					'prompt': message,
					'max_tokens': 150,
					'temperature': 0.5,
					'stop': '\n',
					'n': 1,
					'model': 'text-davinci-002',
					'api_key': apiKey
				}).then(response => {
					const text = response.data.choices[0].text.trim();
					addMessage('You', message);
					addMessage('ChatGPT', text);
					messageInput.value = '';
				}).catch(error => {
					console.error(error);
					addMessage('System', 'Oops, something went wrong with ChatGPT.');
				});
			}
		}

		function addMessage(sender, text) {
			const messageBox = document.createElement('div');
			messageBox.style.marginBottom = '10px';
			messageBox.innerHTML = '<strong>' + sender + ':</strong> ' + text;
			chatbox.appendChild(messageBox);
			chatbox.scrollTop = chatbox.scrollHeight;
		}
	</script>
</body>
</html>

这段代码使用了 Axios 库来发送 POST 请求,获取 ChatGPT 的回复,并将回复显示在聊天框中。要使用此代码,您需要将'YOUR_API_KEY'替换为您的 ChatGPT API 密钥,并将其添加到您的 HTML 文件中。

静态网站 ChatGPT 聊天工具:一键搭建,快速对话

原文地址: https://www.cveoy.top/t/topic/m62D 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录