Vue openAi

来源:https://www.cnblogs.com/psmart/archive/2023/11/15/17833319.html
-Advertisement-
Play Games

1、提示 由於國內註冊 https://api.openai.com 比較麻煩,直接購買的第三方介面和key 淘寶購買,幾塊錢1個月 3、自己娛樂夠用 2、前端框架 Vant 移動端使用 axios 3、創建攔截器,api/request.js /* * @Descripttion: 文件說明 * ...


1、提示

  1. 由於國內註冊 https://api.openai.com 比較麻煩,直接購買的第三方介面和key
  2. 淘寶購買,幾塊錢1個月
    3、自己娛樂夠用

2、前端框架

  1. Vant 移動端使用
  2. axios

3、創建攔截器,api/request.js

/*
 * @Descripttion: 文件說明
 * @version: 0.0.1
 * @Author: pengshuai
 * @Date: 2023-11-01 10:39:22
 * @LastEditors: PengShuai
 * @LastEditTime: 2023-11-02 10:33:28
 */
import axios from 'axios'
// 創建axios實例
const service = axios.create({
  timeout: 300 * 1000, // ms請求超時時間
})

// request攔截器
service.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    // Do something with request error
    Promise.reject(error)
  }
)

// respone攔截器
service.interceptors.response.use(
  (response) => {
    const res = response
    if (res.status !== 200) {
      return Promise.reject(response)
    } else {
      if (res.status === 200) {
        return res.data
      } else {
        return Promise.reject(res.data.message)
      }
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default service

4、創建介面 api/index.js

import service from './request'
// 訪問介面地址
const baseUrl = window.configUrl.openApi
const openAi = (data) =>
  service({
    url: baseUrl + '/v1/chat/completions',
    method: 'post',
    headers: {
      'content-type': 'application/json',
      Authorization:
        'Bearer YOU-KEY-63D8A64444655655C56a0838490e',
    },
    data,
  })
export default { openAi }

5、完整代碼

<!--
 * @Descripttion: 人工智障
 * @version: 0.0.1
 * @Author: PengShuai
 * @Date: 2023-11-10 10:22:33
 * @LastEditors: PengShuai
 * @LastEditTime: 2023-11-10 16:02:25
-->
<template>
  <div class="page">
    <div class="header">
      <nav-bar
        title="人工智障"
        right-text="清空"
        @click-right="onClickRight"
      ></nav-bar>
    </div>
    <div class="main" ref="mainScroll">
      <div
        class="list"
        v-for="(item, index) in params.messages"
        :key="index"
        :class="item.role + 'tr'"
      >
        <div :class="item.role">{{ item.content }}</div>
        <base-loading
          v-if="
            item.role === 'user' &&
            index === params.messages.length - 1 &&
            loading
          "
        ></base-loading>
      </div>
    </div>
    <div class="footer">
      <van-field placeholder="請輸入..." v-model="messages.content">
        <template #button>
          <van-button
            size="small"
            icon="guide-o"
            type="primary"
            @click="onSend"
            @keyup.enter="onSend"
          ></van-button>
        </template>
      </van-field>
    </div>
    <div class="popup" v-if="loading"></div>
  </div>
</template>

<script>
import api from '@/api'
import { NavBar, Field, Button, Notify } from 'vant'
import baseLoading from '@/components/baseLoading'
export default {
  name: 'HomePage',
  components: {
    baseLoading,
    NavBar,
    [Notify.name]: Notify,
    [Field.name]: Field,
    [Button.name]: Button,
  },
  data() {
    return {
      // 參數
      params: {
        messages: [
          {
            role: 'system',
            content: '你好,我是彭帥的人工智障,有什麼可以幫您?',
          },
        ],
        stream: true,
        model: 'gpt-3.5-turbo',
        temperature: 0.5,
        presence_penalty: 0,
        frequency_penalty: 0,
        top_p: 1,
      },
      // 消息列表
      infoList: [],
      // 消息
      messages: {
        role: 'user',
        content: '',
      },
      loading: false,
    }
  },
  methods: {
    /**
     *@Descripttion:點擊右側清空
     *@Author: PengShuai
     *@Date: 2023-11-10 13:13:51
     */
    onClickRight() {
      this.params = {
        messages: [
          {
            role: 'system',
            content: '你好,我是彭帥的人工智障,有什麼可以幫您?',
          },
        ],
        stream: true,
        model: 'gpt-3.5-turbo',
        temperature: 0.5,
        presence_penalty: 0,
        frequency_penalty: 0,
        top_p: 1,
      }
      this.messages.content = ''
    },
    /**
     *@Descripttion:點擊發送
     *@Author: PengShuai
     *@Date: 2023-11-10 13:34:06
     */
    onSend() {
      this.loading = true
      this.params.messages.push(JSON.parse(JSON.stringify(this.messages)))
      let obj = {
        role: '',
        content: '',
      }
      this.messages.content = ''
      this.onBottomScrollClick()
      api
        .openAi(this.params)
        .then((res) => {
          if (res) {
            let info = null
            info = res.split('\n\n')
            info = info.map((obj) => obj.substring(5))
            info.splice(-2)
            info = info.map((obj) => JSON.parse(obj))
            if (info.length > 0) {
              info.forEach((item) => {
                if (item.choices.length > 0) {
                  item.choices.forEach((o) => {
                    if (o.delta.role) {
                      obj.role = o.delta.role
                    } else if (o.delta.content) {
                      obj.content += o.delta.content
                    }
                  })
                }
              })
              this.infoList.push(obj)
            }
            this.params.messages.push(this.infoList[this.infoList.length - 1])
            this.loading = false
            this.onBottomScrollClick()
          }
        })
        .catch((err) => {
          this.loading = false
          Notify({ type: 'danger', message: err })
        })
    },
    /**
     *@Descripttion:滾動條到底部
     *@Author: PengShuai
     *@Date: 2023-11-10 15:38:21
     */
    onBottomScrollClick() {
      this.$nextTick(() => {
        let scroll = this.$refs.mainScroll
        scroll.scrollTo({ top: scroll.scrollHeight, behavior: 'smooth' })
      })
    },
  },
}
</script>

<style lang="less" scoped>
.page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .header {
    border-bottom: 1px solid #ddd;
  }
  .footer {
    border: 1px solid #ddd;
  }
  .main {
    flex: 1;
    margin: 10px 0;
    border: 1px solid #ddd;
    overflow: auto;
  }

  .usertr {
    text-align: right;
  }
  .list {
    .system,
    .assistant {
      margin: 10px 10px 10px 35px;
      text-align: left;
      position: relative;
      padding: 5px 0;
      color: #878787;
      border-bottom: 1px solid #ddd;
      display: inline-block;
      &::after {
        content: '智';
        position: absolute;
        left: -25px;
        top: 5px;
        background: #07c160;
        border-radius: 50%;
        width: 22px;
        height: 22px;
        line-height: 22px;
        text-align: center;
        color: #fff;
        font-size: 12px;
      }
    }
    .user {
      margin: 10px 40px 10px 10px;
      text-align: right;
      position: relative;
      padding: 5px 0;
      color: #505050;
      border-bottom: 1px solid #ddd;
      display: inline-block;
      &::after {
        content: '帥';
        position: absolute;
        right: -25px;
        top: 5px;
        background: #07c160;
        border-radius: 50%;
        width: 22px;
        height: 22px;
        line-height: 22px;
        text-align: center;
        color: #fff;
        font-size: 12px;
      }
    }
  }
  .popup {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>

6、提示 baseLoading 請求loading 組件 可刪除自己寫

<template>
  <div class="baseLoading">
    <div class="loading">
      <span style="--time: 1">智</span>
      <span style="--time: 2">障</span>
      <span style="--time: 3">正</span>
      <span style="--time: 4">在</span>
      <span style="--time: 5">思</span>
      <span style="--time: 6">考</span>
      <span style="--time: 7">中</span>
      <span style="--time: 8">.</span>
      <span style="--time: 9">.</span>
      <span style="--time: 10">.</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'baseLoading',
}
</script>

<style lang="less" scoped>
.loading {
  text-align: center;
}

.loading span {
  display: inline-block;
  font-size: 12px;
  font-weight: bold;
  font-family: 'Courier New', Courier, monospace;
  animation: loading 1s ease-in-out infinite;
  animation-delay: calc(0.1s * var(--time));
  color: #919191;
}

@keyframes loading {
  0% {
    transform: translateY(0px);
  }

  25% {
    transform: translateY(-20px);
  }

  50%,
  100% {
    transform: translateY(0px);
  }
}
</style>


7、示例

8、註意

Tips: 請求返回的數據格式為數組,一個字一個數組,需要自己進行數據整理和拼接。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 這裡簡單總結一下mysql shell訪問資料庫時報MySQL Error 1045 (28000): Access denied for user 'root'@'::1' (using password: YES)的原因以及如何解決這個問題 這裡測試的環境為MySQL 8.0.35,我們先來看看 ...
  • 最近雙十一開門紅期間組內出現了一次因 Mysql 死鎖導致的線上問題,當時從監控可以看到資料庫活躍連接數飆升,導致應用層資料庫連接池被打滿,後續所有請求都因獲取不到連接而失敗 ...
  • 在本文中,我們將介紹GaussDB資料庫中的用戶定義函數重載的概念、用法以及示例。用戶定義函數是 SQL 中常用的“編程工具”,允許我們自定義函數來處理和操作數據。 ...
  • 單機GreatSQL/MySQL調整架構為多副本複製的好處有哪些?為什麼要調整? 性能優化:如果單個GreatSQL伺服器的處理能力達到瓶頸,可能需要通過主從複製、雙主複製或MGR,以及其他高可用方案等來提高整體性能。通過將讀請求分發到多個伺服器,可以大大提高併發處理能力。 高可用性:如果您的應用程 ...
  • 本文利用向量的點積和叉積來判斷點是否線上段上。 基礎知識補充 從零開始的高中數學——向量、向量的點積、帶你一次搞懂點積(內積)、叉積(外積)、Unity游戲開發——向量運算(點乘和叉乘 說明 點積可以用來判斷兩個向量的夾角,如果這個夾角是0或者180度,說明這個點在直線上; 叉積可以用來判斷一個點到 ...
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 一、故事的開始 最近產品又開始整活了,本來是毫無壓力的一周,可以小摸一下魚的,但是突然有一天跟我說要做一個在網頁端截屏的功能。 作為一個工作多年的前端,早已學會了儘可能避開麻煩的需求,只做增刪改查就行! 我立馬開始了我的反駁,我的理由是市 ...
  • 本篇文章從數據中心,事件中心如何協議工作、不依賴環境對vue2.x、vue3.x都可以支持、投產頁面問題定位三個方面進行分析。 ...
  • 介面數據類型與表單提交數據類型,在大多數情況下,大部分屬性的類型是相同的,但很少能做到完全統一。我在之前的工作中經常為了方便,直接將介面數據類型復用為表單內數據類型,在遇到屬性類型不一致的情況時會使用any強制忽略類型錯誤。後來經過自省與思考,這種工作模式會引起各種隱藏bug,一定有更好的工程解決方... ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...