1、进⼊讯⻜开放平台:www.xfyun.cn/
2、点击控制台进⼊后台⻚⾯
3、申请星⽕⼤模型的token
4、下载示例代码
5、借鉴示例代码完成⾃⼰的⼈⼯智能平台
<template>
<div class="ask">
你的问题:
<textarea name="" id="" cols="30" rows="3" v-model="question"></texta
rea>
<button @click="ask">发送</button>
</div>
<div class="answer">
{{ total_res }}
</div>
</template>
<script setup>
import { ref, reactive } from 'vue';
import CryptoJS from 'crypto-js'
const question = ref('')
const APPID = '填写⾃⼰的'
const API_SECRET = '填写⾃⼰的'
const API_KEY = '填写⾃⼰的'
const total_res = ref('');
function getWebsocketUrl() {
return new Promise((resolve, reject) => {
var apiKey = API_KEY
var apiSecret = API_SECRET
var url = 'wss://spark-api.xf-yun.com/v1.1/chat'
var host = location.host
var date = new Date().toGMTString()
var algorithm = 'hmac-sha256'
var headers = 'host date request-line'
var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1.1/ch
at HTTP/1.1`
var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret
)
var signature = CryptoJS.enc.Base64.stringify(signatureSha)
var authorizationOrigin = `api_key="${apiKey}", algorithm="${algo
rithm}", headers="${headers}", signature="${signature}"`
var authorization = btoa(authorizationOrigin)
url = `${url}?authorization=${authorization}&date=${date}&host=${
host}`
resolve(url)
})
}
class TTSRecorder {
constructor({
appId = APPID
} = {}) {
this.appId = appId
this.status = 'init'
}
// 修改状态
setStatus(status) {
this.onWillStatusChange && this.onWillStatusChange(this.status, statu
s)
this.status = status
}
// 连接websocket
connectWebSocket() {
this.setStatus('ttsing')
return 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)
}
})
}
// websocket发送数据
webSocketSend() {
var params = {
"header": {
"app_id": this.appId,
"uid": "fd3f47e4-d"
},
"parameter": {
"chat": {
"domain": "general",
"temperature": 0.5,
"max_tokens": 1024
}
},
"payload": {
"message": {
"text": [
// {
// "role": "user",
// "content": "中国第⼀个皇帝是谁?"
// },
// {
// "role": "assistant",
// "content": "秦始皇"
// },
// {
// "role": "user",
// "content": "秦始皇修的⻓城吗"
// },
// {
// "role": "assistant",
// "content": "是的"
// },
{
"role": "user",
"content": question.value
}
]
}
}
}
console.log(JSON.stringify(params))
this.ttsWS.send(JSON.stringify(params))
}
start() {
total_res.value = ""; // 请清空回答历史
this.connectWebSocket()
}
// websocket接收数据的处理
result(resultData) {
let jsonData = JSON.parse(resultData)
console.log(jsonData);
total_res.value = total_res.value + jsonData.payload.choices.text[0].
content
// $('#output_text').val(total_res)
// console.log(resultData)
// 提问失败
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()
bigModel.setStatus("init")
}
}
}
let bigModel = new TTSRecorder()
function ask() {
if (['init', 'endPlay', 'errorTTS'].indexOf(bigModel.status) > -1) {
bigModel.start()
}
}
</script>
<style scoped>
.ask {
width: 800px;
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 30px;
}
.answer {
width: 800px;
height: 600px;
background-color: aliceblue;
overflow-y: auto;
}
</style>