冲刺记录20
今日任务:添加对话AI
遇到困难:调用接口失败
<template>
<view class="container">
<view v-for="(message, index) in historyTextList" :key="index" :class="{'user-message': message.role === 'user', 'bot-message': message.role === 'assistant'}">
<text>{{ message.content }}</text>
</view>
<view class="fixed-input-container">
<input v-model="TEXT" class="input-field" />
<button class="send-button" @click="sendToSpark()">send</button>
</view>
</view>
</template>
<script>
import * as base64 from "base-64"
import CryptoJS from '../../static/crypto-js/crypto-js.js'
import parser from '../../static/fast-xml-parser/src/parser'
import * as utf8 from "utf8"
import URL from 'url'
export default {
data() {
return {
TEXT:"",
httpUrl: "https://spark-api.xf-yun.com/v3.5/chat",
modelDomain: '',
APPID: '058ab497',
APISecret: 'ODRjYjkxZDkwYzJlN2UyNGM2MjlkZDA2',
APIKey: '9f72399979c03be474a3af799e41cc9b',
sparkResult: '',
historyTextList: [],
tempRes: ''
}
},
methods: {
async sendToSpark() {
let myUrl = await this.getWebSocketUrl();
this.tempRes = "";
let realThis = this;
this.socketTask = uni.connectSocket({
url: myUrl,
method: 'GET',
success: res => {
console.log(res, "ws成功连接...", myUrl)
realThis.wsLiveFlag = true;
}
})
realThis.socketTask.onError((res) => {
console.log("连接发生错误,请检查appid是否填写", res)
})
realThis.socketTask.onOpen((res) => {
this.historyTextList.push({
"role": "user",
"content": this.TEXT
})
console.info("wss的onOpen成功执行...", res)
let params = {
"header": {
"app_id": this.APPID,
"uid": "aef9f963-7"
},
"parameter": {
"chat": {
"domain": this.modelDomain,
"temperature": 0.5,
"max_tokens": 1024
}
},
"payload": {
"message": {
"text": this.historyTextList
}
}
};
this.TEXT = '';
console.log("请求的params:" + JSON.stringify(params))
this.sparkResult = this.sparkResult + "\r\n我:" + this.TEXT + "\r\n"
this.sparkResult = this.sparkResult + "大模型:"
console.log("发送第一帧...", params)
realThis.socketTask.send({
data: JSON.stringify(params),
success() {
console.log('第一帧发送成功')
}
});
});
realThis.socketTask.onMessage((res) => {
console.log('收到API返回的内容:', res.data);
let obj = JSON.parse(res.data)
let dataArray = obj.payload.choices.text;
for (let i = 0; i < dataArray.length; i++) {
realThis.sparkResult = realThis.sparkResult + dataArray[i].content
realThis.tempRes = realThis.tempRes + dataArray[i].content
}
let temp = JSON.parse(res.data)
if (temp.header.code !== 0) {
console.log(`${temp.header.code}:${temp.message}`);
realThis.socketTask.close({
success(res) {
console.log('关闭成功', res)
realThis.wsLiveFlag = false;
},
fail(err) {
console.log('关闭失败', err)
}
})
}
if (temp.header.code === 0) {
if (res.data && temp.header.status === 2) {
realThis.sparkResult = realThis.sparkResult +
"\r\n**********************************************"
this.historyTextList.push({
"role": "assistant",
"content": this.tempRes
})
setTimeout(() => {
realThis.socketTask.close({
success(res) {
console.log('关闭成功', res)
},
fail(err) {
// console.log('关闭失败', err)
}
})
}, 1000)
}
}
})
},
getWebSocketUrl() {
var httpUrlHost = (this.httpUrl).substring(8, 28);
var httpUrlPath = (this.httpUrl).substring(28);
switch (httpUrlPath) {
case "/v1.1/chat":
this.modelDomain = "general";
break;
case "/v2.1/chat":
this.modelDomain = "generalv2";
break;
case "/v3.1/chat":
this.modelDomain = "generalv3";
break;
case "/v3.5/chat":
this.modelDomain = "generalv3.5";
break;
}
return new Promise((resolve, reject) => {
var url = "wss://"+httpUrlHost+httpUrlPath;
var host = "spark-api.xf-yun.com";
var apiKeyName = "api_key";
var date = new Date().toGMTString();
var algorithm = "hmac-sha256";
var headers = "host date request-line";
var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${httpUrlPath} HTTP/1.1`;
var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, this.APISecret);
var signature = CryptoJS.enc.Base64.stringify(signatureSha);
var authorizationOrigin =
`${apiKeyName}="${this.APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
var authorization = base64.encode(authorizationOrigin);
url = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`;
resolve(url);
});
},
}
}
</script>
<style scoped>
.container {
background-image: url('/static/images.jpg'); /* Replace 'background_image.jpg' with the URL of your background image */
background-size: cover; /* Scale the background image to cover the entire container */
min-height: 100vh; /* Set minimum height to cover the entire viewport */
display: flex;
flex-direction: column;
}
.user-message {
display: flex;
justify-content: flex-end;
margin-bottom: 5px;
}
.bot-message {
display: flex;
justify-content: flex-start;
margin-bottom: 5px;
}
.user-message > text,
.bot-message > text {
background-color: #f0f0f0;
padding: 8px;
border-radius: 5px;
max-width: 70%;
}
.bot-message > text {
order: -1; /* Reverses order to display bot messages on the left */
}
.input-container {
display: flex;
justify-content: flex-end;
align-items: center;
margin-top: 10px;
}
.input-field {
background-color: rgba(108, 108, 108, 0.5); /* Transparent black background */
color: white;
border: 1px solid gainsboro;
flex: 1; /* Take up remaining space */
height: 30px; /* Set the height of the input field */
}
.fixed-input-container {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
display: flex;
padding: 10px; /* Adjust padding as needed */
background-color: #fff; /* Adjust background color as needed */
border-top: 1px solid #ccc; /* Add a border at the top for separation */
z-index: 999; /* Ensure it's on top of other content */
}
.send-button {
background-image: url('/static/images (1).jpg'); /* Replace 'your_image_url_here.jpg' with the URL of your image */
background-size: cover; /* Scale the background image to cover the button */
border: none;
margin-left: 10px; /* Add some margin between input field and button */
height: 30px; /* Set the height of the button */
display: flex;
justify-content: center;
align-items: center;
}
</style>