支持切换对话样式

This commit is contained in:
linghaihui 2023-04-09 23:44:21 +08:00
parent 10bd33afda
commit cf4ac6d173
13 changed files with 193 additions and 31 deletions

View File

@ -1,6 +1,6 @@
import {
doRequest,
sid_prefix
sidPrefix
} from "./config"
App({
@ -23,7 +23,7 @@ App({
var data = res.data
if (data && data.length > 0) {
doRequest("/save", "POST", {
"sid": sid_prefix + sid,
"sid": sidPrefix + sid,
"conversations": data
}).then(res => {
that.globalData["saved"] = res.data["saved"]
@ -42,7 +42,7 @@ App({
} else {
that.getSid(sid => {
doRequest("/save", "POST", {
"sid": sid_prefix + sid,
"sid": sidPrefix + sid,
"conversations": conversations,
}).then(res => {
console.log("upload " + conversations.length + " conversations success!")

View File

@ -2,7 +2,7 @@ const app = getApp()
import {
doRequest,
sid_prefix,
sidPrefix,
systemInfo
} from "../../config"
@ -48,7 +48,7 @@ Component({
showShare: false,
loadingData: false,
systemInfo: systemInfo,
height: systemInfo.windowHeight - parseInt(100 / 750 * systemInfo.windowWidth) - ((systemInfo.platform == "ios" || systemInfo.platform == "android") ? 22 : 5)
height: systemInfo.windowHeight - parseInt(100 / 750 * systemInfo.windowWidth) - ((systemInfo.platform == "ios" || systemInfo.platform == "android") ? 22 : 0)
},
methods: {
bindscrolltoupper: function (e) {
@ -68,7 +68,7 @@ Component({
page = Math.ceil((that.data.chatList.length + 1) / 10)
}
doRequest("/query", "GET", {
"sid": sid_prefix + sid,
"sid": sidPrefix + sid,
"page": page,
"size": 10,
}).then(res => {
@ -93,7 +93,7 @@ Component({
if (oldData.length < 10) {
wx.setStorage({
key: "chatList",
data: newData.slice(newData.length - 10),
data: newData.slice(-10),
})
}
if (filterData.length == 0 && e) {
@ -149,7 +149,7 @@ Component({
})
app.getSid(sid => {
doRequest("/delete", "POST", {
"sid": sid_prefix + sid,
"sid": sidPrefix + sid,
"conversation": deleteData
}).then(res => {
console.log(res)

View File

@ -1,7 +1,8 @@
{
"component": true,
"usingComponents": {
"mp-html": "mp-html",
"popup": "../popup/popup"
}
"mp-html": "mp-html",
"popup": "../popup/popup",
"quotes": "../quotes/quotes"
}
}

View File

@ -13,6 +13,7 @@
<mp-html content="{{item.content ? item.content: item.originContent}}" preview-img selectable="{{true}}" markdown="{{true}}" img-cache="{{true}}" lazy-load="{{true}}" use-anchor="{{true}}" scroll-table="{{true}}" container-style="margin-top: -1em;" wx:if="{{!item.showOrigin}}" /><text wx:else user-select="{{true}}" decode="{{true}}">{{item.originContent}}</text>
</view>
</view>
<quotes content="{{item.originContent}}"></quotes>
<view class="suggest">
<view hover-class="suggest-item-hover" class="suggest-item" catchtap="suggestSubmit" data-suggest="{{suggest}}" wx:key="index" wx:for="{{item.suggests}}" wx:for-item="suggest" wx:if="{{suggest && suggest.length > 0}}">{{suggest}}</view>
</view>

View File

@ -0,0 +1,71 @@
// components/quotes/quotes.js
var urlRe = /\[\d+\]:.*/g
Component({
/**
* 组件的属性列表
*/
properties: {
content: {
type: String,
value: "",
observer(nv, ov, path) {
if (nv) {
var quoteUrls = this.getquoteUrls(nv)
this.setData({
quoteUrls: quoteUrls
})
} else {
this.setData({
quoteUrls: []
})
}
}
}
},
/**
* 组件的初始数据
*/
data: {
quoteUrls: []
},
/**
* 组件的方法列表
*/
methods: {
copyUrl: function (e) {
var url = e.currentTarget.dataset.url
wx.setClipboardData({
data: url,
success: function () {
wx.showToast({
title: "链接已复制",
})
}
})
},
getquoteUrls: function (content) {
var quoteUrls = content.match(urlRe)
if (null == quoteUrls) {
return []
}
var res = []
quoteUrls.forEach(k => {
k = k.split(" ")
var i = k[0].match(/\[(\d+)\]/)[1]
var url = k[1]
var host = url.split("/").splice(0, 3).join("/")
var title = k.slice(2).join("").replaceAll('"', "")
res.push({
i,
url,
host,
title
})
})
return res
}
}
})

View File

@ -0,0 +1,4 @@
{
"component": true,
"usingComponents": {}
}

View File

@ -0,0 +1,3 @@
<view wx:if="{{quoteUrls.length > 0}}" class="quote">
<text wx:for="{{quoteUrls}}" data-url="{{item.url}}" data-t="{{item.title}}" class="quote-item" catchtap="copyUrl" wx:key="index" decode="{{true}}">{{item.i}}. {{item.host}} &nbsp;{{item.title}}</text>
</view>

View File

@ -0,0 +1,23 @@
.quote {
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
background-color: #f4f6f8;
border-radius: 0rpx 16rpx 0rpx 16rpx;
padding: 10rpx 16rpx 10rpx 16rpx;
margin-top: -16rpx;
}
.quote-item {
background-color: #D1DBFA;
display: inline-block;
padding: 5rpx;
border-radius: 8rpx;
margin-right: 10rpx;
color: #123BB6;
margin-bottom: 10rpx;
font-size: 24rpx;
cursor: pointer;
word-break: break-all;
min-width: 100%;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

File diff suppressed because one or more lines are too long

View File

@ -2,7 +2,7 @@ import {
doRequest,
SERVER_WSS_HOST,
systemInfo,
sid_prefix
sidPrefix
} from "../../config"
const initHeight = inputPop() ? 22 : 5
@ -32,6 +32,17 @@ try {
} catch (e) {
chatType = "bing"
}
// 对话模式
var chatStyleList = ["creative", "balanced", "precise"]
var chatStyle = chatStyleList[0]
try {
var chatStyle = wx.getStorageSync("chatStyle")
if (!chatStyle) {
chatStyle = chatStyleList[0]
}
} catch (e) {
chatStyle = chatStyleList[0]
}
Date.prototype.format = function (fmt) {
var o = {
@ -84,6 +95,12 @@ Page({
showSearchPop: false,
searchPopMessage: "",
chatType: chatType,
chatStyle: chatStyle,
chatStyleBg: {
creative: "#8B257E",
balanced: "#1B4AEF",
precise: "#005366"
}
},
inputFocus(e) {
if (inputPop()) {
@ -104,7 +121,7 @@ Page({
resetConversation: function (callback) {
app.getSid(sid => {
doRequest("/reset", "GET", {
sid: sid_prefix + sid,
sid: sidPrefix + sid,
}).then(res => {
if (callback) {
callback(res)
@ -175,7 +192,7 @@ Page({
scrollId: "item" + (cht.data.chatList.length - 2),
})
}
}, 500)
}, 300)
},
processData: function (data, suggests, content) {
var robContent = data["data"]["status"]
@ -213,9 +230,10 @@ Page({
var that = this
app.getSid(sid => {
that.sendSocketMessage({
"q": content,
"sid": sid_prefix + sid,
"t": new Date().getTime()
q: content,
sid: sidPrefix + sid,
t: new Date().getTime(),
style: that.data.chatStyle,
})
})
},
@ -226,7 +244,8 @@ Page({
app.getSid(sid => {
doRequest(api, "POST", {
q: content,
sid: sid_prefix + sid,
sid: sidPrefix + sid,
style: that.data.chatStyle,
}).then(res => {
try {
var robContent = ""
@ -553,7 +572,7 @@ Page({
})
app.getSid(sid => {
doRequest("/delete_all", "POST", {
"sid": sid_prefix + sid
"sid": sidPrefix + sid
}).then(res => {
console.log("delete all")
wx.setStorage({
@ -569,18 +588,43 @@ Page({
longPress: function (e) {
var that = this
const cht = app.globalData.cht
var itemList = ["删除全部聊天记录", "切换聊天接口方式", cht.data.closeShareOnCopy ? "打开复制后分享" : "关闭复制后分享"]
var itemList = ["选择对话模式", "删除全部聊天记录", "切换聊天接口方式", cht.data.closeShareOnCopy ? "打开复制后分享" : "关闭复制后分享"]
if ((app.globalData["saved"] && app.globalData["saved"] == 1) || that.data.chatType == "chatgpt") {
itemList = ["删除全部聊天记录", "切换聊天接口方式", cht.data.closeShareOnCopy ? "打开复制后分享" : "关闭复制后分享", that.data.chatType == "bing" ? "切换成ChatGPT" : "切换成New Bing"]
itemList = ["选择对话模式", "删除全部聊天记录", "切换聊天接口方式", cht.data.closeShareOnCopy ? "打开复制后分享" : "关闭复制后分享", that.data.chatType == "bing" ? "切换成ChatGPT" : "切换成New Bing"]
}
wx.showActionSheet({
itemList: itemList,
success(res) {
if (res.tapIndex == 0) {
that.deleteAllChat()
var items = ["更多创造力", "更多平衡", "更多精确"]
items.forEach((v, k) => {
if (that.data.chatStyle == chatStyleList[k]) {
items[k] += "(已选)"
}
})
wx.showActionSheet({
title: "选择对话模式",
itemList: items,
success(res) {
wx.showToast({
title: "已选择“" + items[res.tapIndex] + "”",
icon: "none"
})
var chatStyle = chatStyleList[res.tapIndex]
that.setData({
chatStyle: chatStyle
})
wx.setStorage({
key: "chatStyle",
data: chatStyle,
})
}
})
} else if (res.tapIndex == 1) {
that.switchRequestMethod()
that.deleteAllChat()
} else if (res.tapIndex == 2) {
that.switchRequestMethod()
} else if (res.tapIndex == 3) {
if (cht.data.closeShareOnCopy) {
cht.setData({
closeShareOnCopy: false,
@ -605,7 +649,7 @@ Page({
data: 1,
})
}
} else if (res.tapIndex == 3) {
} else if (res.tapIndex == 4) {
if (that.data.chatType == "chatgpt") {
wx.removeStorage({
key: "usechatgpt",

View File

@ -1,6 +1,6 @@
<chat-box bindsuggestSubmit="onSuggestSubmit" bindcancelReceive="onCancelReceive" bindswitchRequestMethod="switchRequestMethod" catchlongpress="longPress" chatType="{{chatType}}"></chat-box>
<view style="bottom:{{inputBottom}}px; border-radius: 20rpx;margin-left: 1%;width: 98%;min-height: 100rpx;position: fixed;background-color: #f4f6f8;display: flex;align-items:flex-start; z-index: 10000; justify-content: space-between;{{textareaFocus ? 'border: 1px solid #b4bbc4;': ''}}">
<textarea bindfocus="inputFocus" bindblur="inputBlur" value="{{content}}" adjust-position="{{false}}" focus="{{textareaFocus}}" maxlength="2000" auto-height="{{true}}" cursor-spacing="10" bindconfirm="submit" fixed="{{true}}" show-confirm-bar="{{false}}" confirm-type="send" placeholder="{{systemInfo.platform == 'mac' || systemInfo.platform == 'windows' ? '请输入问题,输入>>>提交...': '请输入问题...'}}" style="padding: 10rpx;flex: 9;line-height: normal;" placeholder-style="color: #b4bbc4" catchtap="focus" bindinput="inputData" catchlongpress="scrollBottom"></textarea>
<view style="bottom:{{inputBottom}}px; border-radius: 20rpx;margin-left: 1%;width: 98%;min-height: 100rpx;position: fixed;background-color: #f4f6f8;display: flex;align-items:flex-start; z-index: 10000; justify-content: space-between;border: {{textareaFocus ? '1px': '0px'}} solid {{chatStyleBg[chatStyle]}};">
<textarea bindfocus="inputFocus" bindblur="inputBlur" value="{{content}}" adjust-position="{{false}}" focus="{{textareaFocus}}" maxlength="2000" auto-height="{{true}}" cursor-spacing="10" bindconfirm="submit" fixed="{{true}}" show-confirm-bar="{{false}}" confirm-type="send" placeholder="{{systemInfo.platform == 'mac' || systemInfo.platform == 'windows' ? '请输入问题,输入>>>提交...': '请输入问题...'}}" style="padding: 10rpx;flex: 9;line-height: normal;" placeholder-style="color: {{textareaFocus ? chatStyleBg[chatStyle] : 'b4bbc4'}}" catchtap="focus" bindinput="inputData" catchlongpress="scrollBottom"></textarea>
<view style="background-color: #f4f6f8;color: {{content ? black : '#b4bbc4'}};border-radius: 0 20rpx 20rpx 0;height: 90rpx;cursor: pointer;margin-right: 15rpx;padding-top:10rpx;font-size: 32rpx;" catchtap="submit" wx:if="{{systemInfo.platform != 'ios'}}">发送</view>
</view>
<popup message="{{searchPopMessage}}" wx:if="{{showSearchPop}}" bindPopButtonClick="onPopButtonClick" data-q="{{q}}"></popup>

View File

@ -91,9 +91,10 @@ async def ws_chat(_, ws):
logger.info('[bing] Websocket receive data: %s', data)
sid = data['sid']
q = data['q']
style = data.get('style', 'balanced')
index = 0
last_not_final_text = ''
async for response in get_bot(sid).ask_stream(q, conversation_style=ConversationStyle.creative):
async for response in get_bot(sid).ask_stream(q, conversation_style=ConversationStyle[style]):
final, res = response
if final:
processed_data = await process_data(res, q, sid, auto_reset=1)
@ -147,8 +148,10 @@ async def reset_conversation(sid):
async def do_chat(request):
logger.info('[bing] Http request payload: %s', request.json)
style = request.json.get('style', 'balanced')
return await get_bot(request.json.get('sid')).ask(
request.json.get('q'), conversation_style=ConversationStyle.creative
request.json.get('q'),
conversation_style=ConversationStyle[style],
)
@ -217,6 +220,16 @@ async def openid(request):
# #########################################以下是openid接口##################################
def get_temperature(style):
if style == ConversationStyle.balanced.name:
return 1
elif style == ConversationStyle.creative.name:
return 1.5
elif style == ConversationStyle.precise.name:
return 0.5
return 0.5
@app.websocket('/ws_openai_chat')
async def ws_openai_chat(_, ws):
while True:
@ -227,6 +240,7 @@ async def ws_openai_chat(_, ws):
if not show_chatgpt(sid):
raise Exception('无权限访问此服务')
q = data['q']
style = data.get('style', 'balanced')
# 保存30个对话
history_conversation = OPENAI_CONVERSATION[sid][-30:]
history_conversation.append({
@ -236,7 +250,7 @@ async def ws_openai_chat(_, ws):
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=history_conversation,
temperature=0.8,
temperature=get_temperature(style),
stream=True,
)
chunks = []
@ -281,6 +295,7 @@ async def openai_chat(request):
if not show_chatgpt(sid):
raise Exception('无权限访问此服务')
q = request.json.get('q')
style = request.json.get('style', 'balanced')
history_conversation = OPENAI_CONVERSATION[sid][-30:]
history_conversation.append({
'role': 'user',
@ -289,7 +304,7 @@ async def openai_chat(request):
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=history_conversation,
temperature=0.8,
temperature=get_temperature(style),
stream=True,
)
chunks = []