VUE开发接入ChatGpt教程分析

 4544

页面仿照微信聊天界面,点击机器人图标,弹出聊天框,消息分为用户消息,机器人消息两种,每次用户发送消息,请求后端接口获取chatGPT返回的信息,添加到消息列表中,推送给用户。

不直接通过前端请求chatgpt官方接口,否则会泄露个人的api-key,在官方接口的基础上封装一层,并添加rsa加密,前端请求时进行rsa加密,后端查取数据前,进行rsa解密,防止恶意请求(加密的字符根据个人而定,比如我加密当前时间戳,解密后比较时间戳和当前时间,时差在一分钟之内则有效)

官方接口示例

  1. curl --location --request POST 'https://api.openai.com/v1/completions' \
  2. --header 'Content-Type: application/json' \
  3. --header 'Authorization: Bearer 这里用注册chatgpt后个人的api-key替换' \
  4. --data-raw '{"prompt": "讲个故事", "max_tokens": 2048, "model": "text-davinci-003"}'

VUE前端示例

  1. <template>
  2.     <div>
  3.         <el-avatar @click="viewClick" :size="50" src="https://s1.ax1x.com/2023/02/09/pSWy9QU.png"></el-avatar>
  4.         <el-dialog v-model="viewStatus" title="聊天机器人" width="40%">
  5.             <div id="msgarea" >
  6.                 <div v-for="msg in msgList" :key="msg">
  7.                     <div v-if="msg.isUser">
  8.                         <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
  9.                         <el-card shadow="always"> {{ msg.content }} </el-card>
  10.                     </div>
  11.                     <div v-else>
  12.                         <el-avatar src="https://s1.ax1x.com/2023/02/09/pSWy9QU.png" />
  13.                         <el-card shadow="always"> {{ msg.content }} </el-card>
  14.                     </div>
  15.                 </div>
  16.   
  17.   
  18.             </div>
  19.             <template #footer>
  20.                 <span v-loading="loading">
  21.                     <el-input v-model="input" placeholder="please input" />
  22.                     <el-button type="primary" @click="sendMsg">
  23.                         send
  24.                     </el-button>
  25.                 </span>
  26.             </template>
  27.         </el-dialog>
  28.     </div>
  29. </template>
  30.   
  31. <script>
  32. import { defineComponent, reactive, toRefs } from 'vue'
  33. import { encryptMI } from '@/type/rsa'
  34. import { sendChat } from '@/request/api'
  35. import { requestResultNoti } from '@/request/resultNotification';
  36.   
  37. interface MessageInterface {
  38.     id?: number,
  39.     type?: string,
  40.     isUser: boolean,
  41.     content: string
  42. }
  43. export default defineComponent({
  44.     setup() {
  45.         const data = reactive({
  46.             viewStatus: false,
  47.             icon: "../asset/robot.png",
  48.             input: "",
  49.             count: 0,
  50.             loading: false,
  51.             msgList: [
  52.                 {
  53.                     "id": 0,
  54.                     "isUser": false,
  55.                     "content": "我是您的智能助手,请输入一个问题"
  56.                 }
  57.             ] as Array<MessageInterface>,
  58.             publicKey: '这里是rsa公钥'
  59.         })
  60.   
  61.         const viewClick = () => {
  62.             data.viewStatus = !data.viewStatus
  63.         }
  64.         const scrollToEnd = () => {
  65.             console.log("滚动展示最新消息");
  66.             const element = document.getElementById('msgarea')
  67.             if (element !== null) {
  68.                 element.scrollTop = element.scrollHeight
  69.             }
  70.         }
  71.         const sendMsg = () => {
  72.             if (data.input == "") return
  73.             const msg = {
  74.                 "id": ++data.count,
  75.                 "isUser": true,
  76.                 "content": data.input
  77.             }
  78.             data.msgList.push(msg)
  79.             setTimeout(() => {
  80.                 scrollToEnd()
  81.             }, 1000);
  82.             scrollToEnd()
  83.             const sendmsg = data.input
  84.             data.input = ""
  85.             data.loading = true
  86.             sendChat({
  87.                 prompt: sendmsg,
  88.                 token: encryptMI(new Date().getTime().toString(), data.publicKey) as string
  89.             }).then(
  90.                 res => {
  91.                     requestResultNoti(res);
  92.                     if (res.data.content == undefined) {
  93.                         data.loading = false
  94.   
  95.                     }
  96.                     else {
  97.                         const msgRobot = {
  98.                             "id": ++data.count,
  99.                             "isUser": res.data.isUser,
  100.                             "content": res.data.content
  101.                         }
  102.                         data.msgList.push(msgRobot)
  103.                         data.loading = false
  104.                         setTimeout(() => {
  105.                             scrollToEnd()
  106.                         }, 2000);
  107.                     }
  108.                 })
  109.   
  110.         }
  111.   
  112.         return {
  113.             ...toRefs(data),
  114.             viewClick,
  115.             sendMsg
  116.         }
  117.     }
  118. })
  119. </script>
  120.   
  121. <style scoped>
  122. .user-msg {
  123.     margin-top: 15px;
  124.     margin-bottom: 15px;
  125.     display: inline;
  126.     float: right;
  127. }
  128.   
  129. .msg-card-user {
  130.     width: 550px;
  131.     float: right;
  132. }
  133.   
  134. .robot-msg {
  135.     margin-top: 15px;
  136.     margin-bottom: 15px;
  137.     text-align: left;
  138.     float: left;
  139. }
  140.   
  141. .msg-card-robot {
  142.     width: 550px;
  143.     float: left;
  144. }
  145.   
  146. .msg-area {
  147.     height: 580px;
  148.     overflow-x: hidden;
  149.     overflow-y: auto;
  150. }
  151. </style>

Java后端示例

seivice层

  1. package com.guojian.student.home.service.impl;/**
  2.  * Created on 2023/2/10.
  3.  *
  4.  * [url=home.php?mod=space&uid=686208]@AuThor[/url] GuoJian
  5.  * -version 1.0.0
  6.  */
  7.   
  8. import com.alibaba.fastjson.JSON;
  9. import com.alibaba.fastjson.JSONObject;
  10. import com.guojian.student.home.model.param.ChatParam;
  11. import com.guojian.student.home.model.vo.ChatVO;
  12. import com.guojian.student.home.service.ChatGptService;
  13. import com.guojian.student.home.util.RSAUtils;
  14. import org.apache.http.HttpEntity;
  15. import org.apache.http.HttpStatus;
  16. import org.apache.http.client.ClientProtocolException;
  17. import org.apache.http.client.config.RequestConfig;
  18. import org.apache.http.client.methods.CloseableHttpResponse;
  19. import org.apache.http.client.methods.HttpPost;
  20. import org.apache.http.entity.ContentType;
  21. import org.apache.http.entity.StringEntity;
  22. import org.apache.http.impl.client.CloseableHttpClient;
  23. import org.apache.http.impl.client.HttpClients;
  24. import org.apache.http.util.EntityUtils;
  25. import org.springframework.stereotype.Service;
  26.   
  27. import java.io.IOException;
  28. import java.io.UnsupportedEncodingException;
  29. import java.security.NoSuchAlgorithmException;
  30. import java.security.spec.InvalidKeySpecException;
  31. import java.util.*;
  32.   
  33. /**
  34.  * @ClassName:ChatGptServiceImpl
  35.  * @Author: GuoJian
  36.  * @Date: 2023/2/10 8:57
  37.  * @Description: chatGpt二次封装服务实现
  38.  */
  39. @Service
  40. public class ChatGptServiceImpl implements ChatGptService {
  41.     @Override
  42.     public ChatVO request(ChatParam chatParam){
  43.         String url = "https://api.openai.com/v1/completions";
  44.         Map<String,Object> jparam = new HashMap<>();
  45.         jparam.put("prompt", chatParam.getPrompt());
  46.         jparam.put("max_tokens", 2048);
  47.         jparam.put("model","text-davinci-003");
  48.         Map<String,String> headParams = new HashMap<>();
  49.         headParams.put("Content-Type","application/json");
  50.         headParams.put("Authorization","Bearer 个人aipkey替换这里");
  51.         String resultJson = doPostJson(url, JSONObject.toJSONString(jparam),headParams);
  52.         JSONObject jsonObject = JSON.parseObject(resultJson);
  53.         ChatVO result = new ChatVO();
  54.         result.setContent(jsonObject.getJSONArray("choices").getJSONObject(0).getString("text"));
  55.         result.setIsUser(false);
  56.         return result;
  57.     }
  58.     @Override
  59.     public String decipherin(String ciphertext) throws NoSuchAlgorithmException, InvalidKeySpecException {
  60.         String privateKey = "这里是私钥";
  61.         String decodedData = RSAUtils.privateDecrypt(ciphertext, RSAUtils.getPrivateKey(privateKey)); //传入密文和私钥,得到明文
  62.         return decodedData;
  63.     }
  64.     public static String doPostJson(String url, String params, Map<String,String> headParams) {
  65.         String result = null;
  66.         //1. 获取httpclient对象
  67.         CloseableHttpClient httpClient = HttpClients.createDefault();
  68.         CloseableHttpResponse response = null;
  69.         try {
  70.             //2. 创建post请求
  71.             HttpPost httpPost = new HttpPost(url);
  72.   
  73.             //3.设置请求和传输超时时间
  74.             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(120000).setConnectTimeout(120000).build();
  75.             httpPost.setConfig(requestConfig);
  76.   
  77.             //4.提交参数发送请求
  78.             httpPost.setEntity(new StringEntity(params, ContentType.create("application/json", "utf-8")));
  79.   
  80.             //设置请求头
  81.             for (String head : headParams.keySet()) {
  82.                 httpPost.addHeader(head,headParams.get(head));
  83.             }
  84.   
  85.             response = httpClient.execute(httpPost);
  86.             System.out.println(response);
  87.             //5.得到响应信息
  88.             int statusCode = response.getStatusLine().getStatusCode();
  89.             //6. 判断响应信息是否正确
  90.             if (HttpStatus.SC_OK != statusCode) {
  91.                 //结束请求并抛出异常
  92.                 httpPost.abort();
  93.                 throw new RuntimeException("HttpClient,error status code :" + statusCode);
  94.             }
  95.             //7. 转换成实体类
  96.             HttpEntity entity = response.getEntity();
  97.             if (null != entity) {
  98.                 result = EntityUtils.toString(entity, "UTF-8");
  99.             }
  100.             EntityUtils.consume(entity);
  101.         } catch (UnsupportedEncodingException e) {
  102.             e.printStackTrace();
  103.         } catch (ClientProtocolException e) {
  104.             e.printStackTrace();
  105.         } catch (IOException e) {
  106.             e.printStackTrace();
  107.         } finally {
  108.             //8. 关闭所有资源连接
  109.             if (null != response) {
  110.                 try {
  111.                     response.close();
  112.                 } catch (IOException e) {
  113.                     e.printStackTrace();
  114.                 }
  115.             }
  116.             if (null != httpClient) {
  117.                 try {
  118.                     httpClient.close();
  119.                 } catch (IOException e) {
  120.                     e.printStackTrace();
  121.                 }
  122.             }
  123.         }
  124.         return result;
  125.     }
  126. }

Java后端代码示例

controller层

  1. package com.guojian.student.home.controller;
  2. /**
  3.  * Created on 2023/2/10.
  4.  *
  5.  * @author GuoJian
  6.  * -version 1.0.0
  7.  */
  8.   
  9. import com.guojian.student.home.common.ResponseBean;
  10. import com.guojian.student.home.model.param.ChatParam;
  11. import com.guojian.student.home.service.ChatGptService;
  12. import lombok.extern.slf4j.Slf4j;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.web.bind.annotation.*;
  15. import java.security.NoSuchAlgorithmException;
  16. import java.security.spec.InvalidKeySpecException;
  17.   
  18. /**
  19.  * @ClassName:ChatGptController
  20.  * @Author: GuoJian
  21.  * @Date: 2023/2/10 9:56
  22.  * @Description: chatgpt二次封装controller
  23.  */
  24. @RestController
  25. @RequestMapping("/student/home/api")
  26. @Slf4j
  27. @CrossOrigin
  28. public class ChatGptController {
  29.     @Autowired
  30.     ChatGptService chatGptService;
  31.   
  32.     @RequestMapping(value = "/chatgpt/send", method = RequestMethod.POST)
  33.     public ResponseBean chat(@RequestBody ChatParam param) throws NoSuchAlgorithmException, InvalidKeySpecException {
  34.         if (System.currentTimeMillis() - Long.parseLong(chatGptService.decipherin(param.getToken())) >= 60000) {
  35.             return ResponseBean.fail("无效的token");
  36.         } else {
  37.             try {
  38.                 return ResponseBean.success(chatGptService.request(param));
  39.             } catch (Exception e) {
  40.                 log.error("请求失败:", e);
  41.                 return ResponseBean.fail("请求失败:" + e.getMessage());
  42.             }
  43.         }
  44.     }
  45. }


本文网址:https://www.zztuku.com/index.php/detail-13813.html
站长图库 - VUE开发接入ChatGpt教程分析
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐