接入chatgpt
1首先需要下载包
npm install apenai
2需要引入
引入
const {Configuration, OpenAIApi} = require("openai");
3还需要一个账号,需要自己的API key
开始写代码
1 chatgpt.js
const {Configuration, OpenAIApi} = require("openai");
const {readFileSync, writeFileSync} = require("fs");
const SendMessage = require("../Websocket/send")
const fs = require("fs");
const token = JSON.parse(
readFileSync("../appkey.json")
)
const configuration = new Configuration({
apiKey: token.apikey,//自己的apikey
});
const openai = new OpenAIApi(configuration);
exports.chatgpt = async (types, id, message_id, propmt) => {
//需要上下文支持,所以将上下文写入chatgpt.txt中
try {
let data = readFileSync("chatgpt.txt").toString()
const completion = await openai.createCompletion({
model: "text-davinci-003",
temperature: 0.4,
max_tokens: 1000,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0.6,
stop: [" Human:", " AI:"],
prompt: data + "Human:" + propmt,
});
console.log(completion.data.choices[0]);
let resopone = completion.data.choices[0].text.replace("/\n\t\\\\b/g", "")
writeFileSync("chatgpt.txt", "The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and very friendly.\n\nHuman: Hello, who are you?\nAI: I am an AI created by OpenAI. How can I help you today?\nHuman: " + propmt + "\n" + resopone + "\n")
resopone = resopone.replace("AI:", "")
await SendMessage.SendMessage(types, resopone, id,) //自己封装的发送消息函数
} catch (e) {
if (e) {
await await SendMessage.SendMessage(types, `chatgpt机器人出错了,错误在:${e}`, id,)
}
}
}
2. sendmessage.js
exports.SendMessage = async (types, weather, id) => {
if (types === "private") {
console.log(weather)
const {data: res} = await axios({
method: "post",
url: "http://127.0.0.1:5000/send_private_msg",
data: {
user_id: id,
message: weather,
auto_escape: false,
}
})
console.log(res)
} else {
console.log(weather)
const {data: res} = await axios({
method: "post",
url: "http://127.0.0.1:5000/send_group_msg",
data: {
group_id: id,
message: weather,
auto_escape: true,
}
})
console.log(res)
}
}