VUE开发接入ChatGpt教程分析

#推荐
VUE开发接入ChatGpt教程分析

2026-03-17 2
[!--dianshu--] C币
VIP折扣
    折扣详情
  • 体验VIP会员

    免费

  • 月卡VIP会员

    免费

  • 年卡VIP会员

    免费

  • 永久VIP会员

    免费

查看演示
下载不了?请联系网站客服提交链接错误!
TAG标签: 安装指导

#推荐
VUE开发接入ChatGpt教程分析

2026-03-17 php教程 9999 2
郑重承诺丨总裁主题提供安全交易、信息保真!
TAG标签:
安装指导
[!--dianshu--] C币
VIP权限详情
    会员权限详情
  • 体验VIP会员

    免费

  • 月卡VIP会员

    免费

  • 年卡VIP会员

    免费

  • 永久VIP会员

    免费

开通VIP尊享优惠特权
立即下载 等待添加 升级会员 最新活动
微信扫码咨询 微信扫码咨询

联系电话:18888888888

进入TA的商铺 联系官方客服
详情介绍

欢迎!我白天是个邮递员,晚上就是个有抱负的演员。这是我的网站。我住在天朝的帝都,有条叫做Jack的狗。

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

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

官方接口示例

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

<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="聊天机器人" width="40%">            <div id="msgarea" >                <div v-for="msg in msgList" :key="msg">                    <div v-if="msg.isUser">                        <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />                        <el-card shadow="always"> {{ msg.content }} </el-card>                    </div>                    <div v-else>                        <el-avatar src="https://s1.ax1x.com/2023/02/09/pSWy9QU.png" />                        <el-card shadow="always"> {{ msg.content }} </el-card>                    </div>                </div>              </div>            <template #footer>                <span 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>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": "我是您的智能助手,请输入一个问题"                }            ] as Array<MessageInterface>,            publicKey: '这里是rsa公钥'        })         const viewClick = () => {            data.viewStatus = !data.viewStatus        }        const scrollToEnd = () => {            console.log("滚动展示最新消息");            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>

Java后端示例

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二次封装服务实现 */@Servicepublic 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 个人aipkey替换这里");        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对象        CloseableHttpClient httpClient = HttpClients.createDefault();        CloseableHttpResponse response = null;        try {            //2. 创建post请求            HttpPost httpPost = new HttpPost(url);             //3.设置请求和传输超时时间            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(120000).setConnectTimeout(120000).build();            httpPost.setConfig(requestConfig);             //4.提交参数发送请求            httpPost.setEntity(new StringEntity(params, ContentType.create("application/json", "utf-8")));             //设置请求头            for (String head : headParams.keySet()) {                httpPost.addHeader(head,headParams.get(head));            }             response = httpClient.execute(httpPost);            System.out.println(response);            //5.得到响应信息            int statusCode = response.getStatusLine().getStatusCode();            //6. 判断响应信息是否正确            if (HttpStatus.SC_OK != statusCode) {                //结束请求并抛出异常                httpPost.abort();                throw new RuntimeException("HttpClient,error status code :" + statusCode);            }            //7. 转换成实体类            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. 关闭所有资源连接            if (null != response) {                try {                    response.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (null != httpClient) {                try {                    httpClient.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return result;    }}Java后端代码示例

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@CrossOriginpublic 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("无效的token");        } else {            try {                return ResponseBean.success(chatGptService.request(param));            } catch (Exception e) {                log.error("请求失败:", e);                return ResponseBean.fail("请求失败:" + e.getMessage());            }        }    }}

相关专题
下载地址
  • 提取密码
  • 1561
  • 解压密码
  • DWQwdewq
    立即免费下载
    VUE开发接入ChatGpt教程分析
收藏 (15) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 ()

所有文章为演示数据,不提供下载地址,版权归原作者所有,仅提供演示效果!

CMS主题网 php教程 VUE开发接入ChatGpt教程分析 /showinfo-48-69-0.html

我们只做高端Wordpress主题开发!

常见问题
  • 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用
查看详情

相关文章

帝国CMS二次开发 函数文件      PRinterror()/e/class/connect.phpline 132query()/e/class/db_sql.php line 10fetch1()/e/class/db_sql.php line 30fetch()/e/class/db_sql.php line 22checklevel()/e/class/functions.php line 3414insert_dolog()/e/class/functions.php line 3...
#推荐
2026-03-17 14 C币
帝国CMS8.0父子信息调用方      帝国CMS8.0版新增父子信息功能,让一条信息也能成为一个信息、一个栏目、一个专题、甚至一个网站。本文共有四个部分:一、父子信息功能使用流程。二、调用子信息:可以用索引灵动标签调用。三、父子信息列表访问地址的语法说明。四、进阶:调用当前父子信息...
#推荐
2026-03-17 4 C币
帝国CMS判断当前数据库是      有时候我们需要判断数据库是否包含某字段,就可以使用下面这段SQL语法,$fr=$empire-&gt;fetch1(&quot;SELECT COUNT(*) AS column_exists FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = &amp;#39;$infotb&amp;#39; AND COLUMN_NAME = &amp;#39;money&amp;#39;&quot;);if($fr[&amp;...
#推荐
2026-03-17 4 C币
Python开发一个ChatGPT GU      1、首先去下载这个ChatGPT库,用到的库是这个:https://github.com/acheong08/ChatGPT2、安装这个ChatGPT库:pip3 install revChatGPT==0.0.a423、同目录还需要一个“config.json”:{    &quot;session_token&quot;: &quot;&quot;,    &quot;cf_clearance&quot;: &quot;&quot;,    &quot;user_agent&quot;: &quot;
#推荐
2026-03-17 4 C币
使用CSS Grid Generator拖      如果你是CSS小白,不会使用复杂的UI框架,又需要开发一个响应式网站,那么我的站长站推荐你使用CSS Grid Generator,直接拖拽网格,就可以立即生成响应式CSS代码,复制到自己项目即可使用。使用方法1、首先根据你的项目需求,生成指定的列数和网格数量2、然后拖到...
#推荐
2026-03-17 3 C币
Playwright闲鱼智能监控机      项目介绍Playwright闲鱼智能监控机器人项目,基于 Playwright 和AI过滤分析的闲鱼多任务实时监控与智能分析工具,配备了功能完善的 Web 管理界面。可以实时按规则抓取闲鱼商品,垃圾佬的最爱。闲鱼智能监控机器人:https://github.com/dingyufei615/ai-goof...
#推荐
2026-03-17 3 C币
过年给网站加一对灯笼CSS      马上快过年了,给网站加一对红灯笼,这样才有过年的喜庆劲儿。灯笼是代码生成的无需图片,而且还会摆动。使用方法把HTML下面代码粘贴到网页BODY内任意位子都可以。灯笼的位子可以微调.deng-box的left和right数值。CSS代码&lt;!-- 灯笼代码 --&gt;&lt;div class=&quot;de...
#推荐
2026-03-17 3 C币
ajax上传文件进度条功能示      ajax上传文件时,有时比较耗时,需要在界面上显示下进度信息,获取ajaxSettings中的xhr对象,为它的upload属性绑定progress事件的处理函数前端代码&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt;&lt;meta charset=&quot;utf8&quot;&gt;&lt;title&gt;test upload&lt;/title&gt;&lt;!--jquery--&gt;&lt;script src=&quot;h...
#推荐
2026-03-17 3 C币