node版本比较低,所以没有用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', // 设置响应类型为流
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
因为deepseek 采用流传输会比较快,stream 设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。即使设置responseType为'stream', 浏览器的返回数据也不是如此, 看一下deepseek的解答:
axios-onDownloadProgress.jpg
2.跨域
这个比较简单,设置一下代理就完事了。因为上面我们已经封装了baseURL:'/deepseek', 所以在config中设置一下
dev: {
proxyTable: {
'/deepseek': {
target: 'https://api.deepseek.com/v1',
changeOrigin: true,
pathRewrite: { '^/deepseek': '' }
},
}
}
3.运用
绑定到原型链上:
import DeepSeekSDK from '@/assets/scripts/deepseek'
const deepSeek = new DeepSeekSDK()
Vue.prototype.$deepSeek = deepSeek
页面直接调用:
// 点击按钮事件
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 回复内容
const source = axios.CancelToken.source()
this.cancelToken = source
const filterDataFuc = (content) => {
this.deepseekanser += content
}
await this.$deepSeek.postData(data, filterDataFuc, source)
},
4.效果图
deepseek效果.jpg