vue 項(xiàng)目 接入deepseek

node版本比較低,所以沒(méi)有用openAi的sdk模式,采用瀏覽器axios。

1、封裝deepseek.js
import axios from 'axios'
class DeepSeekSDK {
  constructor () {
    // this.apiKey = 'sk-xxxx'
    this.apiKey = ''
    this.baseURL = '/deepseek'
    this.buffer = ''
    this.client = axios.create({
      baseURL: this.baseURL,
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      }
    })
  }
  async postData (data, filterData, source) {
    try {
      this.buffer = ''
      const response = await this.client.post('/chat/completions', data, {
        responseType: 'text', // 設(shè)置響應(yīng)類(lèi)型為流
        cancelToken: source.token,
        onDownloadProgress: (progressEvent) => {
          const chunk = progressEvent.currentTarget.responseText
          this.buffer += chunk
          let eventEndIndex
          while ((eventEndIndex = this.buffer.indexOf('\n\n')) >= 0) {
            const event = this.buffer.substring(0, eventEndIndex)
            this.buffer = this.buffer.substring(eventEndIndex + 2)
            const lines = event.split('\n')
            for (const line of lines) {
              if (line.startsWith('data: ')) {
                const dataStr = line.substring(6)
                try {
                  const dataJson = JSON.parse(dataStr)
                  filterData(dataJson.choices[0].delta.content || '')
                } catch (e) {
                  console.error('解析JSON失敗', e)
                }
              }
            }
          }
        }
      })
      return response
    } catch (error) {
      console.error('Error posting data:', error)
      throw error
    }
  }
}
export default DeepSeekSDK

因?yàn)閐eepseek 采用流傳輸會(huì)比較快,stream 設(shè)置為 True,將會(huì)以 SSE(server-sent events)的形式以流式發(fā)送消息增量。消息流以 data: [DONE] 結(jié)尾。即使設(shè)置responseType為'stream', 瀏覽器的返回?cái)?shù)據(jù)也不是如此, 看一下deepseek的解答:


axios-onDownloadProgress.jpg
2.跨域

這個(gè)比較簡(jiǎn)單,設(shè)置一下代理就完事了。因?yàn)樯厦嫖覀円呀?jīng)封裝了baseURL:'/deepseek', 所以在config中設(shè)置一下

dev: {
  proxyTable: {
      '/deepseek': {
        target: 'https://api.deepseek.com/v1',
        changeOrigin: true,
        pathRewrite: { '^/deepseek': '' }
      },
  }
}
3.運(yùn)用
綁定到原型鏈上:
import DeepSeekSDK from '@/assets/scripts/deepseek'
const deepSeek = new DeepSeekSDK()
Vue.prototype.$deepSeek = deepSeek
頁(yè)面直接調(diào)用:
// 點(diǎn)擊按鈕事件
async sendDeepSeek () {
      let data = JSON.stringify({
        'messages': [
          {
            'content': 'You are a helpful assistant',
            'role': 'system'
          },
          {
            'content': '你好',
            'role': 'user'
          },
          {
            'content': '你好,有什么幫助么?',
            'role': 'assistant'
          },
          {
            'content': this.deepseekInput,
            'role': 'user'
          }
        ],
        'model': 'deepseek-chat',
        'frequency_penalty': 0,
        'max_tokens': 2048,
        'presence_penalty': 0,
        'response_format': {
          'type': 'text'
        },
        'stop': null,
        'stream': true,
        'stream_options': {
          'include_usage': false
        },
        'temperature': 1,
        'top_p': 1,
        'tools': null,
        'tool_choice': 'none',
        'logprobs': false,
        'top_logprobs': null
      })
      this.deepseekanser = '' // deepseek 回復(fù)內(nèi)容
      const source = axios.CancelToken.source()
      this.cancelToken = source
      const filterDataFuc = (content) => {
        this.deepseekanser += content
      }
      await this.$deepSeek.postData(data, filterDataFuc, source)
    },
4.效果圖
deepseek效果.jpg
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容