本人早先买了一个外网服务器,闲置没用,最近ChatGPT爆火,突发奇想,是否可以利用外网服务器,搭建服务端+网页端来实现国内访问。
说干就干,首先需要准备以下工具:
- chatgpt API 密钥
- 外网服务器(配置nodejs,网上有教程)
获取API Key
- 登录chatgpt官网,点击右上角的登陆,输入邮箱与密码
- 点击“Personal”,选择 View API keys
- 进入 API keys 账户后,点击 Create new secret key 生成密钥
- 在弹出的keys窗口中将密钥复制即可
注意:API key生成一次后就看不到了,所以在第一次生成时注意保存下来
搭建服务端
- 下载依赖模块
npm i openai
npm i dotenv
npm i express
npm i http
npm i socket.io
- 开发服务端程序
const { Configuration, OpenAIApi } = require("openai");//引入openai模块用于配置API key
require('dotenv').config()//引入dotenv模块用于导入API keyconst configuration = new Configuration({apiKey: process.env.OPENAI_API_KEY,//导入API key
});
const openai = new OpenAIApi(configuration);
填充请求结构体,并接收对话消息
const completion = await openai.createCompletion({model: "text-davinci-003",//模型prompt: message,//输入消息temperature: 0.5,max_tokens: 3500,//最大token数量top_p: 1,frequency_penalty: 0,presence_penalty: 0,});return completion.data.choices[0].text;//chatgpt返回文本结果
// 监听连接事件
io.on('connection', function(socket) {console.log('a user connected');// 监听 chat 事件socket.on('chat', async function(msg) {console.log('Me:' + msg);io.emit('chat', "ChatGPT:"+log); // 将消息广播给所有客户端});// 监听断开连接事件socket.on('disconnect', function() {console.log('user disconnected');});
});
// 启动服务器
server.listen(3000, function() {console.log('listening on *:3000');
});
搭建网页端
- 开发网页端程序
//引入表单格式
const socket = io();
const chatOutput = document.getElementById('chat-output');
const chatForm = document.getElementById('chat-form');
const chatInput = document.getElementById('chat-input');
const chatSubmit = document.getElementById('chat-submit');
// 监听来自服务器的 chat 事件
socket.on('chat', function(msg) {const newMsg = document.createElement('div');newMsg.textContent = msg;newMsg.className = 'chat-msg'; // 添加类名newMsg.classList.add('chat-msg', 'received');chatOutput.appendChild(newMsg);
});
// 监听表单提交事件
chatForm.addEventListener('submit', function(e) {e.preventDefault();const msg = chatInput.value;chatInput.value = '';const newMsg = document.createElement('div');newMsg.textContent = "Me:"+msg;newMsg.className = 'chat-msg'; // 添加类名newMsg.classList.add('chat-msg', 'sent');chatOutput.appendChild(newMsg);socket.emit('chat', msg); // 将消息发送给服务器
});
运行
- 服务端运行
node server.js
- 网页端打开页面
https://服务器IP:3000
至此,基于chatGPT API的服务端和网页端搭建完毕,以下是效果展示: