使用星火chatGPT接入vue前端页面

接入科大讯飞的星火chatGPT大模型首先需要有token(现在可以免费领取10万字符)

然后就可以开始接入了,这里无非就是配置自己的 apiKey,apiSecret,appId,然后进行发送WebSocket并且拼接返回值进行显示(注意星火大模型的v1和v2链接有点不一样):

页面:

<template>
    <div style="margin-top:30px;padding-left:10px;padding-right:10px">
      <el-row :gutter="20">
        <el-col :span="16">
            <el-input
                style="margin-left:20px"
                type="textarea"
                placeholder="请输入内容"
                v-model="userInput"
                maxlength="500"
                show-word-limit
                :autosize="{ minRows: 2}"
                resize="none"
            />
        </el-col>
        <el-col :span="8">
            <el-button @click="start" type="primary" style="margin-left:10px;width:50%" :loading="loading">{{ loading? 'ai在拼命思考啦':'提问' }}</el-button>
        </el-col>
      </el-row>
      <div>
        <div v-for="chatConten in finalChat">
            <p style="color:green">我:{{ chatConten.user }}</p>
            <p style="color:red">chatGPT:{{ chatConten.ai }}</p>
        </div>
      </div>
    </div>
  </template>
   
  <script>
  import CryptoJS from 'crypto-js';
   
  export default {
    data() {
      return {
        appId: '你的appid',
        status: 'init',
        ttsWS: null,
        totalRes: '',
        userInput: '',
        aiContentRequest: '',
        finalChat: [],
        loading:false
      };
    },
    methods: {
      getWebsocketUrl() {
        return new Promise((resolve, reject) => {
          const apiKey = '你的apikey';
          const apiSecret = '你的apisecret';
          const url = 'wss://spark-api.xf-yun.com/v1.1/chat'; //这里使用的是星火大模型1.x版本
          const host = window.location.host;
          const date = new Date().toGMTString();
          const algorithm = 'hmac-sha256';
          const headers = 'host date request-line';
          const signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1.1/chat HTTP/1.1`;
          const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
          const signature = CryptoJS.enc.Base64.stringify(signatureSha);
          const authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
          const authorization = window.btoa(authorizationOrigin);
          const finalUrl = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
          console.log(finalUrl)
          resolve(finalUrl);
        });
      },
      setStatus(status) {
        this.status = status;
      },
      connectWebSocket() {
        this.setStatus('ttsing');
        this.getWebsocketUrl().then((url) => {
          let ttsWS;
          if ('WebSocket' in window) {
            ttsWS = new WebSocket(url);
          } else if ('MozWebSocket' in window) {
            ttsWS = new MozWebSocket(url);
          } else {
            alert('浏览器不支持WebSocket');
            return;
          }
          this.ttsWS = ttsWS;
          ttsWS.onopen = (e) => {
            this.webSocketSend();
          };
          ttsWS.onmessage = (e) => {
            this.result(e.data);
          };
          ttsWS.onerror = (e) => {
            clearTimeout(this.playTimeout);
            this.setStatus('error');
            alert('WebSocket报错,请f12查看详情');
            console.error(`详情查看:${encodeURI(url.replace('wss:', 'https:'))}`);
          };
          ttsWS.onclose = (e) => {
            console.log(e);
          };
        });
      },
      webSocketSend() {
        let that = this
        const params = {
          header: {
            app_id: this.appId,
            uid: '随意',
          },
          parameter: {
            chat: {
              domain: 'lite',//如果是chat2这里也需要进行相应修改,(注意:在最新版本中星火将v1版本改成了免费版,并且将v1的domain变成了lite----------2024.11.16
              temperature: 0.5,
              max_tokens: 1024,
            },
          },
          payload: {
            message: {
              text: [
                    {"role": "user", "content": that.userInput}
                ]
            },
          },
        };
        console.log(JSON.stringify(params));
        this.ttsWS.send(JSON.stringify(params));
      },
      start() {
        this.loading = true
        this.totalRes = '';
        this.aiContentRequest = ''
        this.connectWebSocket();
      },
      requestHandle(requestData) {//处理request
        this.aiContentRequest = this.aiContentRequest + requestData.payload.choices.text[0].content
     },
      result(resultData) {
        let jsonData = JSON.parse(resultData);
        //console.log(jsonData)
        this.totalRes += resultData;
        //this.$refs.outputText.value = this.totalRes;
        //加入到ai回答中
        if(jsonData.header.status!==2){//不为结束就进行添加
            this.requestHandle(jsonData)
        }else {
            let contentSomething = {
                ai: this.aiContentRequest,
                user: this.userInput
            }
            this.finalChat.push(contentSomething)
            this.userInput = ''
            this.loading = false
        }
        if (jsonData.header.code !== 0) {
          alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`);
          console.error(`${jsonData.header.code}:${jsonData.header.message}`);
          return;
        }
        if (jsonData.header.code === 0 && jsonData.header.status === 2) {
          this.ttsWS.close();
          this.setStatus('init');
        }
      },
    },
  };
  </script>

 这里需要安装crypto-js这个依赖,crypto-js是一个用于加密和解密的JavaScript库

npm install --save crypto-js

拼接返回值后是这样,样式可以根据自己的需要进行修改,我这边只是粗略拼接了一下。

参考 https://blog.csdn.net/weixin_72186894/article/details/132755700

 

 

 

 

posted @   妞妞猪  阅读(2032)  评论(3编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示