ChatGpt接入個(gè)人的web平臺(tái)作為對(duì)話智能聊天機(jī)器人

從去年就注冊(cè)chatgpt后一直吃灰,最近突然就火了,鋪天蓋地的消息,把自己的賬號(hào)利用起來(lái),把它接到自己開(kāi)發(fā)的web平臺(tái)上面使用,很是方便。

案例展示-實(shí)現(xiàn)方案

圖片[1]-ChatGpt接入個(gè)人的web平臺(tái)作為對(duì)話智能聊天機(jī)器人

頁(yè)面仿照微信聊天界面,點(diǎn)擊機(jī)器人圖標(biāo),彈出聊天框,消息分為用戶消息,機(jī)器人消息兩種,每次用戶發(fā)送消息,請(qǐng)求后端接口獲取chatgpt返回的信息,添加到消息列表中,推送給用戶。
不直接通過(guò)前端請(qǐng)求chatgpt官方接口,否則會(huì)泄露個(gè)人的api-key,在官方接口的基礎(chǔ)上封裝一層,并添加rsa加密,前端請(qǐng)求時(shí)進(jìn)行rsa加密,后端查取數(shù)據(jù)前,進(jìn)行rsa解密,防止惡意請(qǐng)求(加密的字符根據(jù)個(gè)人而定,比如我加密當(dāng)前時(shí)間戳,解密后比較時(shí)間戳和當(dāng)前時(shí)間,時(shí)差在一分鐘之內(nèi)則有效)

官方接口獲取:

curl --location --request POST 'https://api.openai.com/v1/completions' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer 這里用注冊(cè)chatgpt后個(gè)人的api-key替換' \
--data-raw '{"prompt": "講個(gè)故事", "max_tokens": 2048, "model": "text-davinci-003"}'

前端工程代碼:

<template>
    <div>
        <el-avatar @click="viewClick" :size="50" src="https://s1.ax1x.com/2023/02/09/pSWy9QU.png"></el-avatar>
        <el-dialog v-model="viewStatus" title="聊天機(jī)器人" width="40%">
            <div class="msg-area" id="msgarea" >
                <div v-for="msg in msgList" :key="msg">
                    <div class="user-msg" v-if="msg.isUser">
                        <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                        <el-card shadow="always" class="msg-card-user"> {{ msg.content }} </el-card>
                    </div>
                    <div class="robot-msg" v-else>
                        <el-avatar src="https://s1.ax1x.com/2023/02/09/pSWy9QU.png" />
                        <el-card shadow="always" class="msg-card-robot"> {{ msg.content }} </el-card>
                    </div>
                </div>
 
 
            </div>
            <template #footer>
                <span class="dialog-footer" v-loading="loading">
                    <el-input v-model="input" placeholder="please input" />
                    <el-button type="primary" @click="sendMsg">
                        send
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
 
<script lang="ts">
import { defineComponent, reactive, toRefs } from 'vue'
import { encryptMI } from '@/type/rsa'
import { sendChat } from '@/request/api'
import { requestResultNoti } from '@/request/resultNotification';
 
interface MessageInterface {
    id?: number,
    type?: string,
    isUser: boolean,
    content: string
}
export default defineComponent({
    setup() {
        const data = reactive({
            viewStatus: false,
            icon: "../asset/robot.png",
            input: "",
            count: 0,
            loading: false,
            msgList: [
                {
                    "id": 0,
                    "isUser": false,
                    "content": "我是您的智能助手,請(qǐng)輸入一個(gè)問(wèn)題"
                }
            ] as Array<MessageInterface>,
            publicKey: '這里是rsa公鑰'
        })
 
        const viewClick = () => {
            data.viewStatus = !data.viewStatus
        }
        const scrollToEnd = () => {
            console.log("滾動(dòng)展示最新消息");
            const element = document.getElementById('msgarea')
            if (element !== null) {
                element.scrollTop = element.scrollHeight
            }
        }
        const sendMsg = () => {
            if (data.input == "") return
            const msg = {
                "id": ++data.count,
                "isUser": true,
                "content": data.input
            }
            data.msgList.push(msg)
            setTimeout(() => {
                scrollToEnd()
            }, 1000);
            scrollToEnd()
            const sendmsg = data.input
            data.input = ""
            data.loading = true
            sendChat({
                prompt: sendmsg,
                token: encryptMI(new Date().getTime().toString(), data.publicKey) as string
            }).then(
                res => {
                    requestResultNoti(res);
                    if (res.data.content == undefined) {
                        data.loading = false
 
                    }
                    else {
                        const msgRobot = {
                            "id": ++data.count,
                            "isUser": res.data.isUser,
                            "content": res.data.content
                        }
                        data.msgList.push(msgRobot)
                        data.loading = false
                        setTimeout(() => {
                            scrollToEnd()
                        }, 2000);
                    }
                })
 
        }
 
        return {
            ...toRefs(data),
            viewClick,
            sendMsg
        }
    }
})
</script>
 
<style scoped>
.user-msg {
    margin-top: 15px;
    margin-bottom: 15px;
    display: inline;
    float: right;
}
 
.msg-card-user {
    width: 550px;
    float: right;
}
 
.robot-msg {
    margin-top: 15px;
    margin-bottom: 15px;
    text-align: left;
    float: left;
}
 
.msg-card-robot {
    width: 550px;
    float: left;
}
 
.msg-area {
    height: 580px;
    overflow-x: hidden;
    overflow-y: auto;
}
</style>

后端seivice層:

package com.guojian.student.home.service.impl;/**
 * Created on 2023/2/10.
 *
 * [url=home.php?mod=space&uid=686208]@AuThor[/url] GuoJian
 * -version 1.0.0
 */
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guojian.student.home.model.param.ChatParam;
import com.guojian.student.home.model.vo.ChatVO;
import com.guojian.student.home.service.ChatGptService;
import com.guojian.student.home.util.RSAUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.*;
 
/**
 * @ClassName:ChatGptServiceImpl
 * @Author: GuoJian
 * @Date: 2023/2/10 8:57
 * @Description: chatGpt二次封裝服務(wù)實(shí)現(xiàn)
 */
@Service
public class ChatGptServiceImpl implements ChatGptService {
    @Override
    public ChatVO request(ChatParam chatParam){
        String url = "https://api.openai.com/v1/completions";
        Map<String,Object> jparam = new HashMap<>();
        jparam.put("prompt", chatParam.getPrompt());
        jparam.put("max_tokens", 2048);
        jparam.put("model","text-davinci-003");
        Map<String,String> headParams = new HashMap<>();
        headParams.put("Content-Type","application/json");
        headParams.put("Authorization","Bearer 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");
        String resultJson = doPostJson(url, JSONObject.toJSONString(jparam),headParams);
        JSONObject jsonObject = JSON.parseObject(resultJson);
        ChatVO result = new ChatVO();
        result.setContent(jsonObject.getJSONArray("choices").getJSONObject(0).getString("text"));
        result.setIsUser(false);
        return result;
    }
    @Override
    public String decipherin(String ciphertext) throws NoSuchAlgorithmException, InvalidKeySpecException {
        String privateKey = "這里是私鑰";
        String decodedData = RSAUtils.privateDecrypt(ciphertext, RSAUtils.getPrivateKey(privateKey)); //傳入密文和私鑰,得到明文
        return decodedData;
    }
    public static String doPostJson(String url, String params, Map<String,String> headParams) {
        String result = null;
        //1. 獲取httpclient對(duì)象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            //2. 創(chuàng)建post請(qǐng)求
            HttpPost httpPost = new HttpPost(url);
 
            //3.設(shè)置請(qǐng)求和傳輸超時(shí)時(shí)間
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(120000).setConnectTimeout(120000).build();
            httpPost.setConfig(requestConfig);
 
            //4.提交參數(shù)發(fā)送請(qǐng)求
            httpPost.setEntity(new StringEntity(params, ContentType.create("application/json", "utf-8")));
 
            //設(shè)置請(qǐng)求頭
            for (String head : headParams.keySet()) {
                httpPost.addHeader(head,headParams.get(head));
            }
 
            response = httpClient.execute(httpPost);
            System.out.println(response);
            //5.得到響應(yīng)信息
            int statusCode = response.getStatusLine().getStatusCode();
            //6. 判斷響應(yīng)信息是否正確
            if (HttpStatus.SC_OK != statusCode) {
                //結(jié)束請(qǐng)求并拋出異常
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            //7. 轉(zhuǎn)換成實(shí)體類
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //8. 關(guān)閉所有資源連接
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

后端controller層:

package com.guojian.student.home.controller;/**
 * Created on 2023/2/10.
 *
 * @author GuoJian
 * -version 1.0.0
 */
 
import com.guojian.student.home.common.ResponseBean;
import com.guojian.student.home.model.param.ChatParam;
import com.guojian.student.home.service.ChatGptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
 
/**
 * @ClassName:ChatGptController
 * @Author: GuoJian
 * @Date: 2023/2/10 9:56
 * @Description: chatgpt二次封裝controller
 */
@RestController
@RequestMapping("/student/home/api")
@Slf4j
@CrossOrigin
public class ChatGptController {
    @Autowired
    ChatGptService chatGptService;
 
    @RequestMapping(value = "/chatgpt/send", method = RequestMethod.POST)
    public ResponseBean chat(@RequestBody ChatParam param) throws NoSuchAlgorithmException, InvalidKeySpecException {
        if (System.currentTimeMillis() - Long.parseLong(chatGptService.decipherin(param.getToken())) >= 60000) {
            return ResponseBean.fail("無(wú)效的token");
        } else {
            try {
                return ResponseBean.success(chatGptService.request(param));
            } catch (Exception e) {
                log.error("請(qǐng)求失敗:", e);
                return ResponseBean.fail("請(qǐng)求失敗:" + e.getMessage());
            }
        }
    }
}

效果展示:

圖片[2]-ChatGpt接入個(gè)人的web平臺(tái)作為對(duì)話智能聊天機(jī)器人

網(wǎng)絡(luò)需要國(guó)外的接口,沒(méi)有梯子響應(yīng)很慢,每個(gè)請(qǐng)求響應(yīng)在20秒~1分鐘不等。

------本頁(yè)內(nèi)容已結(jié)束,喜歡請(qǐng)分享------
溫馨提示:由于項(xiàng)目或工具都有失效性,如遇到不能做的項(xiàng)目或不能使用的工具,可以根據(jù)關(guān)鍵詞在站點(diǎn)搜索相關(guān)內(nèi)容,查看最近更新的或者在網(wǎng)頁(yè)底部給我們留言反饋。
? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊467 分享
評(píng)論 搶沙發(fā)

請(qǐng)登錄后發(fā)表評(píng)論

    暫無(wú)評(píng)論內(nèi)容