QQ机器人接入ChatGpt(基于go-cqhttp)

914 阅读1分钟

什么是chatgpt?

ChatGPT是OpenAI开发的一个大型预训练语言模型。它是GPT-3模型的变体,GPT-3经过训练,可以在对话中生成类似人类的文本响应。ChatGPT 旨在用作聊天机器人,我们可以对其进行微调,以完成各种任务,如回答问题、提供信息或参与对话。与许多使用预定义的响应或规则生成文本的聊天机器人不同,ChatGPT经过了训练,可以根据接收到的输入生成响应,从而生成更自然、更多样化的响应。为了让我们的机器人解决更多的问题,我们可以接入chatgpt

接入chatgpt

1首先需要下载openai提供的包

  • npm install apenai

2需要引入

  • 引入

3还需要一个chatgpt账号,需要自己的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,)   //自己封装的发送QQ消息函数        
    } 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)
    }

}