This commit is contained in:
weipengfei 2023-09-14 16:23:08 +08:00
parent 9614403d5e
commit ee7b9a341e
12 changed files with 2933 additions and 2769 deletions

View File

@ -23,9 +23,9 @@
watch: { // latex
latex: {
handler(newval, oldval) {
console.log("--------- 监视latex的变化 ----------")
console.log("oldval", oldval);
console.log("newval", newval);
// console.log("--------- latex ----------")
// console.log("oldval", oldval);
// console.log("newval", newval);
this.mathlab = newval;
this.$forceUpdate();
},
@ -44,9 +44,9 @@
methods: {
//
receiveLab(newValue, oldValue, ownerVm, vm) {
console.log("--------- 接收逻辑层发送的数据 ----------")
console.log("newValue", newValue);
console.log("oldValue", oldValue);
// console.log("--------- ----------")
// console.log("newValue", newValue);
// console.log("oldValue", oldValue);
this.mathlab = newValue;
@ -87,16 +87,16 @@
},
svg: {
scale: 1.2
scale: 1.0
}
};
(function() {
var script = document.createElement('script')
script.id = 'MathJax-script'
// cdn
script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js'
// script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js'
// script.src = 'static/tex-svg.js'; // svgchtml
// script.src = 'static/tex-chtml.js';
script.src = 'static/tex-chtml.js';
document.head.appendChild(script)
})();
console.log("initMathJax() window.MathJax", window.MathJax);

View File

@ -1,23 +1,33 @@
{
"pages": [ //pageshttps://uniapp.dcloud.io/collocation/pages
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "讯飞AI"
}
},
"pages": [ //pageshttps://uniapp.dcloud.io/collocation/pages
{
"path": "pages/index/chat",
"style": {
"navigationBarTitleText": "讯飞星火"
}
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "讯飞AI",
"bounce": "none",
"softinputMode": "adjustResize"
}
}, {
"path": "pages/index/chat",
"style": {
"navigationBarTitleText": "讯飞星火",
"bounce": "none"
}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "人工智能",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
},
"uniIdRouter": {}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "人工智能",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
},
"uniIdRouter": {},
"condition": { //
"current": 0, //(list )
"list": [{
"name": "", //
"path": "", //
"query": "" //onLoad
}]
}
}

View File

@ -1,547 +1,165 @@
<template>
<view class="wrapper">
<view class="tips color_fff size_12 align_c" :class="{ 'show':ajax.loading }" @tap="getHistoryMsg">{{ajax.loadText}}
</view>
<view class="box-1" id="list-box">
<view class="talk-list">
<view v-for="(item,index) in talkList" :key="index" :id="`msg-${item.id}`">
<view class="item flex_col" :class=" item.type == 1 ? 'push':'pull' ">
<image :src="item.pic" mode="aspectFill" class="pic"></image>
<!-- <view v-if="talkList.length-1==index" class="content multiline-text">{{c_content}}</view> -->
<view class="content multiline-text">
<!-- <rich-text :nodes="item.content"></rich-text> -->
<bing-math class="bing-math" :latex="item.content"></bing-math>
</view>
</view>
</view>
</view>
</view>
<view class="box-2">
<view class="flex_col">
<view class="flex_grow">
<input type="text" class="content" v-model="content" placeholder="请输入聊天内容" @confirm="send"
placeholder-style="color:#DDD;" :cursor-spacing="6">
</view>
<button class="send" @tap="send">发送</button>
</view>
</view>
</view>
<view>
带上下文问题(可修改)<input v-model="TEXT" style="border: 1px solid gainsboro;" />
<button style="background-color: blue;color: white;" @click="sendToSpark()">发送给大模型</button>
<text style="width: 90%;flex-wrap:wrap">{{sparkResult}}</text>
</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 fetch from 'miniprogram-fetch';
import axios from 'axios';
import BingMath from "@/components/bing-math/bing-math.vue"
export default {
components: {
'bing-math': BingMath
},
data() {
return {
talkList: [],
ajax: {
rows: 20, //
page: 1, //
flag: false, //
loading: false, //
loadText: '正在获取消息'
},
content: '',
c_content: '',
n_content: '',
TEXT: '你好,我的名字叫大王',
APPID: '2eda6c2e', //
APISecret: 'MDEyMzE5YTc5YmQ5NjMwOTU1MWY4N2Y2',
APIKey: '12ec1f9d113932575fc4b114a2f60ffd',
sparkResult: '',
historyTextList: [], // token12000,使
tempRes: '', //
}
},
mounted() {
this.$nextTick(() => {
// this.getHistoryMsg();
});
},
onPageScroll(e) {
if (e.scrollTop < 5) {
// this.getHistoryMsg();
}
},
watch: {
n_content(n, o) {
this.c_content = n;
}
},
methods: {
copyText(str) {
uni.setClipboardData({
data: str,
success: function () {
uni.showToast({
icon: 'none',
title: '复制成功'
});
}
});
},
//
getHistoryMsg() {
if (!this.ajax.flag) {
return; //
}
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"
export default {
// https://spark-api.xf-yun.com/v1.1/chat V1.5 domain general
// https://spark-api.xf-yun.com/v2.1/chat V2.0 domain generalv2
data() {
return {
TEXT: '你好,我的名字叫大王',
APPID: '2eda6c2e', //
APISecret: 'MDEyMzE5YTc5YmQ5NjMwOTU1MWY4N2Y2',
APIKey: '12ec1f9d113932575fc4b114a2f60ffd',
sparkResult: '',
historyTextList: [], // token12000,使
tempRes: '' //
}
},
methods: {
async sendToSpark() {
let myUrl = await this.getWebSocketUrl();
this.tempRes = "";
// this.sparkResult = "";
let realThis = this;
this.socketTask = uni.connectSocket({
//url: encodeURI(encodeURI(myUrl).replace(/\+/g, '%2B')),
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)
// ..........................................
console.log('open成功...')
let params = {
"header": {
"app_id": this.APPID,
"uid": "aef9f963-7"
},
"parameter": {
"chat": {
"domain": "generalv2",
"temperature": 0.5,
"max_tokens": 1024
}
},
"payload": {
"message": {
"text": this.historyTextList
}
}
};
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({ // uni
data: JSON.stringify(params),
success() {
console.log('第一帧发送成功')
}
});
});
// ES7 async/await 使
let get = async () => {
this.hideLoadTips();
this.ajax.flag = false;
let data = await this.joinHistoryMsg();
//
realThis.socketTask.onMessage((res) => {
console.log('收到API返回的内容', res.data);
let obj = JSON.parse(res.data)
// console.log(""+obj.payload);
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
}
// realThis.sparkResult =realThis.sparkResult+
let temp = JSON.parse(res.data)
// console.log("0726",temp.header.code)
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
})
/* let dataArray= obj.payload.choices.text;
for(let i=0;i<dataArray.length;i++){
realThis.sparkResult =realThis.sparkResult+ dataArray[i].content
} */
setTimeout(() => {
realThis.socketTask.close({
success(res) {
console.log('关闭成功', res)
},
fail(err) {
// console.log('', err)
}
})
}, 1000)
}
}
})
},
//
getWebSocketUrl() {
return new Promise((resolve, reject) => {
// https://spark-api.xf-yun.com/v1.1/chat V1.5 domain general
// https://spark-api.xf-yun.com/v2.1/chat V2.0 domain generalv2
var url = "wss://spark-api.xf-yun.com/v2.1/chat";
var host = "spark-api.xf-yun.com";
var apiKeyName = "api_key";
console.log(new Date().toGMTString());
var date = new Date().toGMTString();
var algorithm = "hmac-sha256";
var headers = "host date request-line";
var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2.1/chat 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}`;
console.log('----- 模拟数据格式,供参考 -----');
console.log(data); //
// 使
let selector = '';
if (this.ajax.page > 1) {
//
selector = `#msg-${this.talkList[0].id}`;
} else {
//
selector = `#msg-${data[data.length-1].id}`;
}
//
this.talkList = [...data, ...this.talkList];
// Vue.js Vue.nextTick
this.$nextTick(() => {
//
this.setPageScrollTo(selector);
this.hideLoadTips(true);
if (data.length < this.ajax.rows) {
//
//
} else {
this.ajax.page++;
// 200ms
setTimeout(() => {
this.ajax.flag = true;
}, 200)
}
})
}
get();
},
//
joinHistoryMsg() {
let join = () => {
let arr = [];
//
let startIndex = (this.ajax.page - 1) * this.ajax.rows;
let endIndex = startIndex + this.ajax.rows;
for (let i = startIndex; i < endIndex; i++) {
arr.push({
"id": i, // ID
"content": `这是历史记录的第${i+1}条消息`, //
"type": Math.random() > 0.5 ? 1 : 0, // 1 0 ,
"pic": "/static/avatar.png" //
})
}
/*
颠倒数组中元素的顺序将最新的数据排在本次接口返回数据的最后面
后端接口按 消息的时间降序查找出当前页的数据后再将本页数据按消息时间降序排序返回
这是数据的重点因为页面滚动条和上拉加载历史的问题
*/
arr.reverse();
return arr;
}
// ES6 Promise
return new Promise((done, fail) => {
// setTimeout ajax
setTimeout(() => {
let data = join();
done(data);
}, 1500);
})
},
//
setPageScrollTo(selector) {
let view = uni.createSelectorQuery().in(this).select(selector);
view.boundingClientRect((res) => {
uni.pageScrollTo({
scrollTop: res.top - 30, // -30
duration: 0
});
}).exec();
},
//
hideLoadTips(flag) {
if (flag) {
this.ajax.loadText = '消息获取成功';
setTimeout(() => {
this.ajax.loading = false;
}, 300);
} else {
this.ajax.loading = true;
this.ajax.loadText = '正在获取消息';
}
},
//
send() {
if (!this.content) {
uni.showToast({
title: '请输入有效的内容',
icon: 'none'
})
return;
}
//
let data = {
"id": new Date().getTime(),
"content": this.content,
"type": 1,
"pic": "/static/avatar.png"
}
this.TEXT = this.content;
this.sendToSpark();
this.talkList.push(data);
this.talkList.push({
"id": new Date().getTime(),
"content": '',
"type": 2,
"pic": "/static/avatar.png"
});
this.$nextTick(() => {
//
this.content = '';
uni.pageScrollTo({
scrollTop: 999999, //
duration: 0
});
})
},
async sendToSpark() {
let myUrl = await this.getWebSocketUrl();
this.tempRes = "";
// this.sparkResult = "";
let realThis = this;
this.socketTask = uni.connectSocket({
//url: encodeURI(encodeURI(myUrl).replace(/\+/g, '%2B')),
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)
// ..........................................
console.log('open成功...')
let params = {
"header": {
"app_id": this.APPID,
"uid": "aef9f963-7"
},
"parameter": {
"chat": {
"domain": "generalv2",
"temperature": 0.5,
"max_tokens": 1024
}
},
"payload": {
"message": {
"text": this.historyTextList
}
}
};
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({ // uni
data: JSON.stringify(params),
success() {
console.log('第一帧发送成功')
}
});
});
//
realThis.socketTask.onMessage((res) => {
console.log('收到API返回的内容', res.data);
let obj = JSON.parse(res.data)
// console.log(""+obj.payload);
let dataArray = obj.payload.choices.text;
for (let i = 0; i < dataArray.length; i++) {
realThis.sparkResult = realThis.sparkResult + dataArray[i].content;
this.talkList[this.talkList.length - 1].content += dataArray[i].content;
this.n_content = this.talkList[this.talkList.length - 1].content;
realThis.tempRes = realThis.tempRes + dataArray[i].content
}
this.$nextTick(() => {
uni.pageScrollTo({
scrollTop: 9999999,
})
})
// realThis.sparkResult =realThis.sparkResult+
let temp = JSON.parse(res.data)
// console.log("0726",temp.header.code)
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
})
/* let dataArray= obj.payload.choices.text;
for(let i=0;i<dataArray.length;i++){
realThis.sparkResult =realThis.sparkResult+ dataArray[i].content
} */
setTimeout(() => {
realThis.socketTask.close({
success(res) {
console.log('关闭成功', res)
},
fail(err) {
// console.log('', err)
}
})
}, 1000)
}
}
})
},
//
getWebSocketUrl() {
return new Promise((resolve, reject) => {
// https://spark-api.xf-yun.com/v1.1/chat V1.5 domain general
// https://spark-api.xf-yun.com/v2.1/chat V2.0 domain generalv2
var url = "wss://spark-api.xf-yun.com/v2.1/chat";
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 /v2.1/chat 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}`;
// console.log(url)
// console.log(url)
resolve(url);
});
},
}
}
});
},
}
}
</script>
<style lang="scss">
@import "../../lib/global.scss";
<style>
page {
background-color: #F3F3F3;
font-size: 28rpx;
}
.wrapper {
height: auto !important;
}
/* 加载数据提示 */
.tips {
position: fixed;
left: 0;
top: var(--window-top);
width: 100%;
z-index: 9;
background-color: rgba(0, 0, 0, 0.15);
height: 72rpx;
line-height: 72rpx;
transform: translateY(-80rpx);
transition: transform 0.3s ease-in-out 0s;
&.show {
transform: translateY(0);
}
}
.box-1 {
width: 100%;
height: auto;
padding-bottom: 100rpx;
box-sizing: content-box;
/* 兼容iPhoneX */
margin-bottom: 0;
margin-bottom: constant(safe-area-inset-bottom);
margin-bottom: env(safe-area-inset-bottom);
}
.multiline-text {
white-space: pre-line;
/* 或 white-space: pre-wrap; */
}
.box-2 {
position: fixed;
left: 0;
width: 100%;
bottom: 0;
height: auto;
z-index: 2;
border-top: #e5e5e5 solid 1px;
box-sizing: content-box;
background-color: #F3F3F3;
/* 兼容iPhoneX */
padding-bottom: 0;
padding-bottom: constant(safe-area-inset-bottom);
padding-bottom: env(safe-area-inset-bottom);
>view {
padding: 0 20rpx;
height: 100rpx;
}
.content {
background-color: #fff;
height: 64rpx;
padding: 0 20rpx;
border-radius: 6rpx;
font-size: 28rpx;
}
.send {
background-color: #2573fb;
color: #fff;
height: 64rpx;
margin-left: 20rpx;
border-radius: 6rpx;
padding: 0;
width: 120rpx;
line-height: 62rpx;
&:active {
background-color: #1573fb;
}
}
}
.talk-list {
padding-bottom: 20rpx;
/* 消息项,基础类 */
.item {
padding: 20rpx 20rpx 0 20rpx;
align-items: flex-start;
align-content: flex-start;
color: #333;
.pic {
width: 92rpx;
height: 92rpx;
border-radius: 50%;
border: #fff solid 1px;
}
.content {
padding: 20rpx;
border-radius: 4px;
max-width: 500rpx;
word-break: break-all;
line-height: 52rpx;
position: relative;
}
/* 收到的消息 */
&.pull {
.content {
margin-left: 32rpx;
background-color: #fff;
&::after {
content: '';
display: block;
width: 0;
height: 0;
border-top: 16rpx solid transparent;
border-bottom: 16rpx solid transparent;
border-right: 20rpx solid #fff;
position: absolute;
top: 30rpx;
left: -18rpx;
}
}
}
/* 发出的消息 */
&.push {
/* 主轴为水平方向起点在右端。使不修改DOM结构也能改变元素排列顺序 */
flex-direction: row-reverse;
.content {
margin-right: 32rpx;
background-color: #2573fb;
color: #fff;
&::after {
content: '';
display: block;
width: 0;
height: 0;
border-top: 16rpx solid transparent;
border-bottom: 16rpx solid transparent;
border-left: 20rpx solid #2573fb;
position: absolute;
top: 30rpx;
right: -18rpx;
}
}
}
}
}
.bing-math{
margin: 0 !important;
padding: 0 !important;
}
</style>

View File

@ -1,165 +1,618 @@
<template>
<view>
带上下文问题(可修改)<input v-model="TEXT" style="border: 1px solid gainsboro;" />
<button style="background-color: blue;color: white;" @click="sendToSpark()">发送给大模型</button>
<text style="width: 90%;flex-wrap:wrap">{{sparkResult}}</text>
</view>
<view class="wrapper">
<view class="tips color_fff size_12 align_c" :class="{ 'show':ajax.loading }" @tap="getHistoryMsg">{{ajax.loadText}}
</view>
<view class="placeholder"></view>
<view class="box-1" id="list-box" ref="box">
<view class="talk-list">
<view v-for="(item,index) in talkList" :key="index" :id="`msg-${item.id}`">
<view class="item flex_col" :class=" item.type == 1 ? 'push':'pull' ">
<image :src="item.pic" mode="aspectFill" class="pic"></image>
<view v-if="talkList.length-1==index" class="content multiline-text">
<!-- <rich-text :nodes="item.content"></rich-text> -->
<bing-math :key="`math-${item.id}`" class="bing-math" :latex="c_content"></bing-math>
</view>
<view v-else class="content multiline-text">
<!-- <rich-text :nodes="item.content"></rich-text> -->
<bing-math :key="`math-${item.id}`" class="bing-math" :latex="item.content"></bing-math>
</view>
</view>
</view>
</view>
</view>
<!-- <view v-show="showplc" :style="{'min-height': (keyboardHeight+200)+'px'}" class="placeholder">显示</view> -->
<view class="box-2">
<view class="flex_col">
<view class="flex_grow">
<input type="text" class="content" v-model="content" placeholder="请输入聊天内容" @focus="focus" @confirm="send"
placeholder-style="color:#DDD;" :cursor-spacing="6">
</view>
<button class="send" @tap="send">发送</button>
</view>
</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"
export default {
// https://spark-api.xf-yun.com/v1.1/chat V1.5 domain general
// https://spark-api.xf-yun.com/v2.1/chat V2.0 domain generalv2
data() {
return {
TEXT: '你好,我的名字叫大王',
APPID: '2eda6c2e', //
APISecret: 'MDEyMzE5YTc5YmQ5NjMwOTU1MWY4N2Y2',
APIKey: '12ec1f9d113932575fc4b114a2f60ffd',
sparkResult: '',
historyTextList: [], // token12000,使
tempRes: '' //
}
},
methods: {
async sendToSpark() {
let myUrl = await this.getWebSocketUrl();
this.tempRes = "";
// this.sparkResult = "";
let realThis = this;
this.socketTask = uni.connectSocket({
//url: encodeURI(encodeURI(myUrl).replace(/\+/g, '%2B')),
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)
// ..........................................
console.log('open成功...')
let params = {
"header": {
"app_id": this.APPID,
"uid": "aef9f963-7"
},
"parameter": {
"chat": {
"domain": "generalv2",
"temperature": 0.5,
"max_tokens": 1024
}
},
"payload": {
"message": {
"text": this.historyTextList
}
}
};
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({ // uni
data: JSON.stringify(params),
success() {
console.log('第一帧发送成功')
}
});
});
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 fetch from 'miniprogram-fetch';
import axios from 'axios';
import BingMath from "@/components/bing-math/bing-math.vue"
export default {
components: {
'bing-math': BingMath
},
data() {
return {
talkList: [],
ajax: {
rows: 20, //
page: 1, //
flag: false, //
loading: false, //
loadText: '正在获取消息'
},
keyboardHeight: 0,
showplc: true,
content: '',
c_content: '',
n_content: '',
timer: '',
TEXT: '你好,我的名字叫大',
APPID: '2eda6c2e', //
APIKey: '12ec1f9d113932575fc4b114a2f60ffd',
APISecret: 'MDEyMzE5YTc5YmQ5NjMwOTU1MWY4N2Y2',
sparkResult: '',
historyTextList: [], // token12000,使
tempRes: '', //
}
},
mounted() {
this.$nextTick(() => {
this.getHistoryMsg();
});
uni.onKeyboardHeightChange(e => {
let h = this.keyboardHeight;
this.keyboardHeight = e.height;
if(e.height==0)h *= -1;
else h = e.height;
uni.createSelectorQuery().selectViewport().scrollOffset(function(res) {
const scrollTop = res.scrollTop; //
uni.pageScrollTo({
scrollTop: scrollTop + h, //
duration: 0 // 300ms300ms
});
}).exec();
})
},
beforeDestroy() {
// #ifdef APP-PLUS
uni.offKeyboardHeightChange();
// #endif
},
onPageScroll(e) {
if (e.scrollTop < 5) {
this.getHistoryMsg();
}
},
watch: {
n_content(n, o) {
// this.c_content = n;
if (this.timer) clearInterval(this.timer);
let cl = this.c_content.length;
let nc = this.n_content.split('')
this.timer = setInterval(() => {
if (cl < nc.length) {
this.c_content += nc[cl];
cl++;
if (cl % 6 == 0) this.$nextTick(()=>{
uni.pageScrollTo({
scrollTop: 999999,
})
// uni.createSelectorQuery()
// .in(this)
// .select('.box-1')
// .boundingClientRect((rect) => {
// const height = rect?.height;
// console.log(height, rect);
// })
// .exec();
})
} else {
clearInterval(this.timer);
this.$nextTick(() => {
uni.pageScrollTo({
scrollTop: 9999999,
})
})
}
}, 60)
}
},
methods: {
copyText(str) {
uni.setClipboardData({
data: str,
success: function() {
uni.showToast({
icon: 'none',
title: '复制成功'
});
}
});
},
//
getHistoryMsg() {
if (!this.ajax.flag) {
return; //
}
//
realThis.socketTask.onMessage((res) => {
console.log('收到API返回的内容', res.data);
let obj = JSON.parse(res.data)
// console.log(""+obj.payload);
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
}
// realThis.sparkResult =realThis.sparkResult+
let temp = JSON.parse(res.data)
// console.log("0726",temp.header.code)
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
})
/* let dataArray= obj.payload.choices.text;
for(let i=0;i<dataArray.length;i++){
realThis.sparkResult =realThis.sparkResult+ dataArray[i].content
} */
setTimeout(() => {
realThis.socketTask.close({
success(res) {
console.log('关闭成功', res)
},
fail(err) {
// console.log('', err)
}
})
}, 1000)
}
}
})
},
//
getWebSocketUrl() {
return new Promise((resolve, reject) => {
// https://spark-api.xf-yun.com/v1.1/chat V1.5 domain general
// https://spark-api.xf-yun.com/v2.1/chat V2.0 domain generalv2
var url = "wss://spark-api.xf-yun.com/v2.1/chat";
var host = "spark-api.xf-yun.com";
var apiKeyName = "api_key";
console.log(new Date().toGMTString());
var date = new Date().toGMTString();
var algorithm = "hmac-sha256";
var headers = "host date request-line";
var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2.1/chat 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}`;
// ES7 async/await 使
let get = async () => {
this.hideLoadTips();
this.ajax.flag = false;
let data = await this.joinHistoryMsg();
// console.log(url)
console.log('----- 模拟数据格式,供参考 -----');
console.log(data); //
// 使
let selector = '';
if (this.ajax.page > 1) {
//
selector = `#msg-${this.talkList[0].id}`;
} else {
//
selector = `#msg-${data[data.length-1].id}`;
}
//
this.talkList = [...data, ...this.talkList];
// Vue.js Vue.nextTick
this.$nextTick(() => {
//
this.setPageScrollTo(selector);
this.hideLoadTips(true);
if (data.length < this.ajax.rows) {
//
//
} else {
this.ajax.page++;
// 200ms
setTimeout(() => {
this.ajax.flag = true;
}, 200)
}
})
}
get();
},
//
joinHistoryMsg() {
let join = () => {
let arr = [];
//
let startIndex = (this.ajax.page - 1) * this.ajax.rows;
let endIndex = startIndex + this.ajax.rows;
for (let i = startIndex; i < endIndex; i++) {
arr.push({
"id": i, // ID
"content": `这是历史记录的第${i+1}条消息`, //
"type": Math.random() > 0.5 ? 1 : 0, // 1 0 ,
"pic": "/static/avatar.png" //
})
}
/*
颠倒数组中元素的顺序将最新的数据排在本次接口返回数据的最后面
后端接口按 消息的时间降序查找出当前页的数据后再将本页数据按消息时间降序排序返回
这是数据的重点因为页面滚动条和上拉加载历史的问题
*/
arr.reverse();
return arr;
}
// ES6 Promise
return new Promise((done, fail) => {
// setTimeout ajax
setTimeout(() => {
let data = join();
done(data);
}, 1500);
})
},
focus(){
uni.pageScrollTo({
top: this.keyboardHeight
})
},
//
setPageScrollTo(selector) {
let view = uni.createSelectorQuery().in(this).select(selector);
view.boundingClientRect((res) => {
uni.pageScrollTo({
scrollTop: res.top - 30, // -30
duration: 0
});
}).exec();
},
//
hideLoadTips(flag) {
if (flag) {
this.ajax.loadText = '消息获取成功';
setTimeout(() => {
this.ajax.loading = false;
}, 300);
} else {
this.ajax.loading = true;
this.ajax.loadText = '正在获取消息';
}
},
//
send() {
if (!this.content) {
uni.showToast({
title: '请输入有效的内容',
icon: 'none'
})
return;
}
//
let data = {
"id": new Date().getTime(),
"content": this.content,
"type": 1,
"pic": "/static/avatar.png"
}
this.TEXT = this.content;
this.n_content = '';
this.c_content = '';
this.talkList.push(data);
this.talkList.push({
"id": new Date().getTime(),
"content": '',
"type": 2,
"pic": "/static/avatar.png"
});
this.$nextTick(() => {
//
this.content = '';
uni.pageScrollTo({
scrollTop: 999999, //
duration: 0
});
})
this.sendToSpark();
},
async sendToSpark() {
let myUrl = await this.getWebSocketUrl();
this.tempRes = "";
// this.sparkResult = "";
let realThis = this;
this.socketTask = uni.connectSocket({
//url: encodeURI(encodeURI(myUrl).replace(/\+/g, '%2B')),
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)
// ..........................................
console.log('open成功...')
let params = {
"header": {
"app_id": this.APPID,
"uid": "aef9f963-7"
},
"parameter": {
"chat": {
"domain": "generalv2",
"temperature": 0.5,
"max_tokens": 1024
}
},
"payload": {
"message": {
"text": this.historyTextList
}
}
};
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({ // uni
data: JSON.stringify(params),
success() {
console.log('第一帧发送成功')
}
});
});
//
realThis.socketTask.onMessage((res) => {
console.log('收到API返回的内容', res.data);
let obj = JSON.parse(res.data)
// console.log(""+obj.payload);
let dataArray = obj.payload.choices.text;
for (let i = 0; i < dataArray.length; i++) {
realThis.sparkResult = realThis.sparkResult + dataArray[i].content;
this.talkList[this.talkList.length - 1].content += dataArray[i].content;
this.n_content = this.talkList[this.talkList.length - 1].content;
realThis.tempRes = realThis.tempRes + dataArray[i].content
}
// realThis.sparkResult =realThis.sparkResult+
let temp = JSON.parse(res.data)
// console.log("0726",temp.header.code)
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
})
/* let dataArray= obj.payload.choices.text;
for(let i=0;i<dataArray.length;i++){
realThis.sparkResult =realThis.sparkResult+ dataArray[i].content
} */
setTimeout(() => {
realThis.socketTask.close({
success(res) {
console.log('关闭成功', res)
},
fail(err) {
// console.log('', err)
}
})
}, 1000)
}
}
})
},
//
getWebSocketUrl() {
return new Promise((resolve, reject) => {
// https://spark-api.xf-yun.com/v1.1/chat V1.5 domain general
// https://spark-api.xf-yun.com/v2.1/chat V2.0 domain generalv2
var url = "wss://spark-api.xf-yun.com/v2.1/chat";
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 /v2.1/chat 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}`;
// console.log(url)
resolve(url);
});
},
}
}
});
},
}
}
</script>
<style>
<style lang="scss">
@import "../../lib/global.scss";
page {
background-color: #f5f5f5;
font-size: 28rpx;
}
.wrapper {
height: auto !important;
}
/* 加载数据提示 */
.tips {
position: fixed;
left: 0;
top: var(--window-top);
width: 100%;
z-index: 9;
background-color: rgba(0, 0, 0, 0.15);
height: 72rpx;
line-height: 72rpx;
transform: translateY(-80rpx);
transition: transform 0.3s ease-in-out 0s;
&.show {
transform: translateY(0);
}
}
.box-1 {
width: 100%;
height: auto;
padding-bottom: 100rpx;
box-sizing: content-box;
/* 兼容iPhoneX */
margin-bottom: 0;
margin-bottom: constant(safe-area-inset-bottom);
margin-bottom: env(safe-area-inset-bottom);
}
.multiline-text {
white-space: pre-line;
/* 或 white-space: pre-wrap; */
}
.box-2 {
position: fixed;
left: 0;
width: 100%;
bottom: 0;
height: auto;
z-index: 2;
border-top: #e5e5e5 solid 1px;
box-sizing: content-box;
background-color: #f5f5f5;
transform: translateY(0); /* 初始化 transform 属性 */
transition: transform 0.3s ease; /* 添加过渡效果 */
/* 兼容iPhoneX */
padding-bottom: 0;
padding-bottom: constant(safe-area-inset-bottom);
padding-bottom: env(safe-area-inset-bottom);
>view {
padding: 0 20rpx;
height: 100rpx;
}
.content {
background-color: #fff;
height: 64rpx;
padding: 0 20rpx;
border-radius: 6rpx;
font-size: 28rpx;
}
.send {
background-color: #2573fb;
color: #fff;
height: 64rpx;
margin-left: 20rpx;
border-radius: 6rpx;
padding: 0;
width: 120rpx;
line-height: 62rpx;
&:active {
background-color: #1573fb;
}
}
}
.talk-list {
padding-bottom: 20rpx;
/* 消息项,基础类 */
.item {
padding: 20rpx 20rpx 0 20rpx;
align-items: flex-start;
align-content: flex-start;
color: #333;
.pic {
width: 92rpx;
height: 92rpx;
border-radius: 50%;
border: #fff solid 1px;
}
.content {
padding: 20rpx;
border-radius: 4px;
max-width: 500rpx;
word-break: break-all;
line-height: 52rpx;
position: relative;
}
/* 收到的消息 */
&.pull {
.content {
min-width: 20rpx;
min-height: 52rpx;
margin-left: 32rpx;
background-color: #fff;
&::after {
content: '';
display: block;
width: 0;
height: 0;
border-top: 16rpx solid transparent;
border-bottom: 16rpx solid transparent;
border-right: 20rpx solid #fff;
position: absolute;
top: 30rpx;
left: -18rpx;
}
}
}
/* 发出的消息 */
&.push {
/* 主轴为水平方向起点在右端。使不修改DOM结构也能改变元素排列顺序 */
flex-direction: row-reverse;
.content {
min-width: 20rpx;
min-height: 52rpx;
margin-right: 32rpx;
background-color: #2573fb;
color: #fff;
&::after {
content: '';
display: block;
width: 0;
height: 0;
border-top: 16rpx solid transparent;
border-bottom: 16rpx solid transparent;
border-left: 20rpx solid #2573fb;
position: absolute;
top: 30rpx;
right: -18rpx;
}
}
}
}
}
.bing-math {
margin: 0 !important;
padding: 0 !important;
}
.placeholder {
width: 100vw;
background-color: #1573fb;
// background-color: transparent;
// transform: translateY(0); /* transform */
// transition: transform 0.3s ease; /* */
}
</style>

1
static/tex-chtml.js Normal file

File diff suppressed because one or more lines are too long

1
static/tex-svg.js Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,8 +1,8 @@
var isReady=false;var onReadyCallbacks=[];
var isServiceReady=false;var onServiceReadyCallbacks=[];
var __uniConfig = {"pages":["pages/index/index","pages/index/chat"],"window":{"navigationBarTextStyle":"black","navigationBarTitleText":"人工智能","navigationBarBackgroundColor":"#F8F8F8","backgroundColor":"#F8F8F8"},"darkmode":false,"nvueCompiler":"uni-app","nvueStyleCompiler":"uni-app","renderer":"auto","splashscreen":{"alwaysShowBeforeRender":true,"autoclose":false},"appname":"xunfeiAi","compilerVersion":"3.8.12","entryPagePath":"pages/index/chat","entryPageQuery":"","realEntryPagePath":"pages/index/index","networkTimeout":{"request":60000,"connectSocket":60000,"uploadFile":60000,"downloadFile":60000}};
var __uniRoutes = [{"path":"/pages/index/index","meta":{"isQuit":true},"window":{"navigationBarTitleText":"讯飞AI"}},{"path":"/pages/index/chat","meta":{},"window":{"navigationBarTitleText":"讯飞星火"}}];
var __uniConfig = {"pages":["pages/index/index","pages/index/chat"],"window":{"navigationBarTextStyle":"black","navigationBarTitleText":"人工智能","navigationBarBackgroundColor":"#F8F8F8","backgroundColor":"#F8F8F8"},"darkmode":false,"nvueCompiler":"uni-app","nvueStyleCompiler":"uni-app","renderer":"auto","splashscreen":{"alwaysShowBeforeRender":true,"autoclose":false},"appname":"xunfeiAi","compilerVersion":"3.8.12","entryPagePath":"pages/index/index","networkTimeout":{"request":60000,"connectSocket":60000,"uploadFile":60000,"downloadFile":60000}};
var __uniRoutes = [{"path":"/pages/index/index","meta":{"isQuit":true},"window":{"navigationBarTitleText":"讯飞AI","bounce":"none","softinputMode":"adjustResize"}},{"path":"/pages/index/chat","meta":{},"window":{"navigationBarTitleText":"讯飞星火","bounce":"none"}}];
__uniConfig.onReady=function(callback){if(__uniConfig.ready){callback()}else{onReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"ready",{get:function(){return isReady},set:function(val){isReady=val;if(!isReady){return}const callbacks=onReadyCallbacks.slice(0);onReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
__uniConfig.onServiceReady=function(callback){if(__uniConfig.serviceReady){callback()}else{onServiceReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"serviceReady",{get:function(){return isServiceReady},set:function(val){isServiceReady=val;if(!isServiceReady){return}const callbacks=onServiceReadyCallbacks.slice(0);onServiceReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
service.register("uni-app-config",{create(a,b,c){if(!__uniConfig.viewport){var d=b.weex.config.env.scale,e=b.weex.config.env.deviceWidth,f=Math.ceil(e/d);Object.assign(__uniConfig,{viewport:f,defaultFontSize:Math.round(f/20)})}return{instance:{__uniConfig:__uniConfig,__uniRoutes:__uniRoutes,global:void 0,window:void 0,document:void 0,frames:void 0,self:void 0,location:void 0,navigator:void 0,localStorage:void 0,history:void 0,Caches:void 0,screen:void 0,alert:void 0,confirm:void 0,prompt:void 0,fetch:void 0,XMLHttpRequest:void 0,WebSocket:void 0,webkit:void 0,print:void 0}}}});

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"@platforms":["android","iPhone","iPad"],"id":"__UNI__9620511","name":"xunfeiAi","version":{"name":"1.0.0","code":"100"},"description":"","launch_path":"__uniappview.html","developer":{"name":"","email":"","url":""},"permissions":{"UniNView":{"description":"UniNView原生渲染"}},"plus":{"useragent":{"value":"uni-app","concatenate":true},"splashscreen":{"target":"id:1","autoclose":true,"waiting":true,"delay":0},"popGesture":"close","launchwebview":{"render":"always","id":"1","kernel":"WKWebview"},"statusbar":{"immersed":"supportedDevice","style":"dark","background":"#F8F8F8"},"usingComponents":true,"nvueStyleCompiler":"uni-app","compilerVersion":3,"distribute":{"google":{"permissions":["<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>","<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>","<uses-permission android:name=\"android.permission.VIBRATE\"/>","<uses-permission android:name=\"android.permission.READ_LOGS\"/>","<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>","<uses-feature android:name=\"android.hardware.camera.autofocus\"/>","<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>","<uses-permission android:name=\"android.permission.CAMERA\"/>","<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>","<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>","<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>","<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>","<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>","<uses-feature android:name=\"android.hardware.camera\"/>","<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"]},"apple":{},"plugins":{"audio":{"mp3":{"description":"Android平台录音支持MP3格式文件"}}}},"uniStatistics":{"enable":false},"arguments":"{\"id\":0,\"name\":\"pages/index/chat\",\"pathName\":\"pages/index/chat\",\"query\":\"\"}","allowsInlineMediaPlayback":true,"uni-app":{"compilerVersion":"3.8.12","control":"uni-v3","nvueCompiler":"uni-app","renderer":"auto","nvue":{"flex-direction":"column"},"nvueLaunchMode":"normal"},"launch_path":"__uniappview.html"},"arguments":{"pathName":"pages/index/chat","query":""}}
{"@platforms":["android","iPhone","iPad"],"id":"__UNI__9620511","name":"xunfeiAi","version":{"name":"1.0.0","code":"100"},"description":"","launch_path":"__uniappview.html","developer":{"name":"","email":"","url":""},"permissions":{"UniNView":{"description":"UniNView原生渲染"}},"plus":{"useragent":{"value":"uni-app","concatenate":true},"splashscreen":{"target":"id:1","autoclose":true,"waiting":true,"delay":0},"popGesture":"close","launchwebview":{"render":"always","id":"1","kernel":"WKWebview"},"statusbar":{"immersed":"supportedDevice","style":"dark","background":"#F8F8F8"},"usingComponents":true,"nvueStyleCompiler":"uni-app","compilerVersion":3,"distribute":{"google":{"permissions":["<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>","<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>","<uses-permission android:name=\"android.permission.VIBRATE\"/>","<uses-permission android:name=\"android.permission.READ_LOGS\"/>","<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>","<uses-feature android:name=\"android.hardware.camera.autofocus\"/>","<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>","<uses-permission android:name=\"android.permission.CAMERA\"/>","<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>","<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>","<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>","<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>","<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>","<uses-feature android:name=\"android.hardware.camera\"/>","<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"]},"apple":{},"plugins":{"audio":{"mp3":{"description":"Android平台录音支持MP3格式文件"}}}},"uniStatistics":{"enable":false},"arguments":"{\"name\":\"\",\"path\":\"\",\"query\":\"\",\"id\":0}","allowsInlineMediaPlayback":true,"uni-app":{"compilerVersion":"3.8.12","control":"uni-v3","nvueCompiler":"uni-app","renderer":"auto","nvue":{"flex-direction":"column"},"nvueLaunchMode":"normal"},"launch_path":"__uniappview.html"}}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long