添加Bard和星火API支持 (#551)

* 修复后台API反代地址未能正确显示的问题

* 更新渲染页面配置

* 添加个人聊天模式配置

* 将用户数据获取改到common中

* 修复错误的渲染页面参数

* 修复bug

* 添加Live2D

* 修复渲染页面错误

* 修复渲染传入值

* 更新渲染

* 修复图表渲染bug

* 调整live2d模型大小

* 修复live2d无法关闭问题

* 修复错误的传值

* 修复ai命名

* 更新渲染

* 添加用户独立设定

* 更新渲染配置适配个人设置

* 修复合并导致的渲染文件异常删除

* 修复用户数据缺失问题

* 修复旧版本数据缺失问题

* 修复bing参数不存在问题,兼容miao的截图

* 修复受限token重试时不被排除的问题

* 修复个人模式下结束对话的模式错误

* 更新渲染页面,将预览版转为正式版

* 修复传统渲染无法调用截图功能的问题

* 文字模式也进行一次缓存

* 更新README

* Update README.md

* 更新渲染

* 更新渲染页面

* 添加版本信息

* 遗漏参数

* 丢失引用

* 补充路由

* 添加云转码功能

* 判断node-silk是否正常合成

* 云转码提示

* 修复图片渲染出错

* 云转码支持发送Buffer

* 添加云转码模式支持

* 更新描述

* 更新后台渲染页面

* 更新配置

* 更新渲染页面

* 添加云渲染

* 修复错误的接口调用

* 修复遗漏的数据转换

* 修复获取的图片数据异常问题

* 更新后台配置

* 更新渲染页面

* 修复云渲染访问地址错误

* 更新渲染页面

* 修复遗漏的模型文件

* 修复live2d问题

* 更新live2d以及相关配置

* 修复遗漏的数据参数

* 修复新live2d情况下云渲染错误的问题

* 适配云渲染1.1.2等待参数

* 添加云服务api检查

* 更新渲染页面

* 添加live2d加载检测

* 修复错误的属性判断

* 添加云渲染DPR

* 更新sydney支持内容生成

* 修改文件模式语音转码接收模式

* 添加云转码时recordUrl检查

* 更新后台配置项

* 修复错误的文本描述

* 更新后台页面

* 添加全局对话模式设置,更新后台面板

* 添加第三方渲染服务适配

* 修复第三方服务器live2d加载导致的渲染失败问题

* 修复后台地址无法实时保存的问题

* 添加live2d模型透明度设置

* 合并更新

* 更新渲染页面

* 更新渲染页面

* 使dpr对本地渲染也生效

* 更新渲染页面

* 添加网页截图功能

* 添加后台配置项

* 添加配置导出和导入功能

* 运行通过参数传递用户token

* 登录时将token作为参数返回

* 修复错误

* 添加密码修改和用户删除接口

* 修正密码比对

* 修复user错误

* 优化数据保存时的返回值

* 添加系统额外服务检查api

* 添加AccessToken配置

* 修复错误的导入提示

* 添加ws连接

* 添加ws用户信息获取

* 修复错误的循环

* 修正ws参数

* 添加群消息获取权限

* 添加用户多端登录支持

* 修复错误的路径引用

* 修复错误的路径引用

* 修复错误

* 修复页面数据获取失败问题

* 修复异常的中断

* 添加配置视图

* 更新配置面板

* 添加用户版本信息

* 更新配置视图

* 修复错误的视图绑定

* 修改视图文件位置,添加mediaLink相关代码

* 修复错误的视图配置绑定

* 更新依赖,添加qq消息组件初始化信息获取

* 修复异常的群名称无法获取问题

* 修改注释

* 撤销对management的错误合并

* 添加Sydney图片识别功能

* 更新配置文件和后台页面

* 修改view配置

* 修复node版本过低导致的FormData无法调用,尝试添加反代

* 国外图片识别不使用反代

* fix: 修复云转码导致的语音重复发送问题

* fix: 修复qq消息可越权获取的问题

* feat: 添加代理post操作

* fix: 修复一些字符串格式的数字导致的配置加载错误

* fix: 修复错误的云服务api网址格式

* fix: 修复错误的云转码接口调用格式

* fix: 修复错误的精度

* 添加配置项适配

* feat: 添加群消息合并功能

* 添加历史记录的消息已读标签

* feat: 添加设定相关接口

* improvement: 在多少绘图失败后尝试使用cn进行绘图

* fix: 修复bing可能存在的无标题引用导致的错误

* fix: 修复绘图获取失败的问题

* 添加bard支持

* feat: 添加图片处理

* 添加bard图片处理能力

* 添加锅巴描述

* fix: 修复空图片链接报错问题

* 添加星火api支持,尚未连接上下文

* feat: 添加星火api上下文

* feat: 增加星火设定

* 添加调试信息

* 添加星火v2支持

* 修复连接地址错误

* feat: 添加星火助手功能

* 添加图片处理和群组消息结束

* feat: 添加星火图片识别支持

* 改回全部使用form-data,优化文本

* 添加对私人星火助手的支持

* 添加xhweb错误内容输出

* 添加星火预设问题库重写

* feat: 添加星火回复内容替换,添加锅巴配置

* 添加星火助手支持

* fix: 修复星火空设定时额外占用消息

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
This commit is contained in:
HalcyonAlcedo 2023-08-24 22:33:23 +08:00 committed by GitHub
parent 3b1641ca5f
commit c2c6ea43de
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 1174 additions and 87 deletions

View file

@ -39,6 +39,7 @@ import { SlackClaudeClient } from '../utils/slack/slackClient.js'
import { getPromptByName } from '../utils/prompts.js'
import BingDrawClient from '../utils/BingDraw.js'
import XinghuoClient from '../utils/xinghuo/xinghuo.js'
import Bard from '../utils/bard.js'
import { JinyanTool } from '../utils/tools/JinyanTool.js'
import { SendVideoTool } from '../utils/tools/SendBilibiliTool.js'
import { KickOutTool } from '../utils/tools/KickOutTool.js'
@ -161,6 +162,14 @@ export class chatgpt extends plugin {
/** 执行方法 */
fnc: 'xh'
},
{
reg: '^#星火助手',
fnc: 'newxhBotConversation'
},
{
reg: '^#星火(搜索|查找)助手',
fnc: 'searchxhBot'
},
{
/** 命令正则匹配 */
reg: toggleMode === 'at' ? '^[^#][sS]*' : '^#chat[^gpt][sS]*',
@ -248,7 +257,7 @@ export class chatgpt extends plugin {
* @param e
* @returns {Promise<boolean>}
*/
async bingCaptcha (e) {
async bingCaptcha(e) {
let bingTokens = JSON.parse(await redis.get('CHATGPT:BING_TOKENS'))
if (!bingTokens) {
await e.reply('尚未绑定必应token:必应过码必须绑定token')
@ -302,36 +311,41 @@ export class chatgpt extends plugin {
async destroyConversations(e) {
const userData = await getUserData(e.user_id)
const use = (userData.mode === 'default' ? null : userData.mode) || await redis.get('CHATGPT:USE')
await redis.del(`CHATGPT:WRONG_EMOTION:${e.sender.user_id}`)
await redis.del(`CHATGPT:WRONG_EMOTION:${(e.isGroup && Config.groupMerge) ? e.group_id.toString() : e.sender.user_id}`)
if (use === 'claude') {
// let client = new SlackClaudeClient({
// slackUserToken: Config.slackUserToken,
// slackChannelId: Config.slackChannelId
// })
// await client.endConversation()
await redis.del(`CHATGPT:SLACK_CONVERSATION:${e.sender.user_id}`)
await redis.del(`CHATGPT:SLACK_CONVERSATION:${(e.isGroup && Config.groupMerge) ? e.group_id.toString() : e.sender.user_id}`)
await e.reply('claude对话已结束')
return
}
if (use === 'xh') {
await redis.del(`CHATGPT:CONVERSATIONS_XH:${e.sender.user_id}`)
await redis.del(`CHATGPT:CONVERSATIONS_XH:${(e.isGroup && Config.groupMerge) ? e.group_id.toString() : e.sender.user_id}`)
await e.reply('星火对话已结束')
return
}
if (use === 'bard') {
await redis.del(`CHATGPT:CONVERSATIONS_BARD:${(e.isGroup && Config.groupMerge) ? e.group_id.toString() : e.sender.user_id}`)
await e.reply('Bard对话已结束')
return
}
let ats = e.message.filter(m => m.type === 'at')
const isAtMode = Config.toggleMode === 'at'
if (isAtMode) ats = ats.filter(item => item.qq !== Bot.uin)
if (ats.length === 0) {
if (use === 'api3') {
await redis.del(`CHATGPT:QQ_CONVERSATION:${e.sender.user_id}`)
await redis.del(`CHATGPT:QQ_CONVERSATION:${(e.isGroup && Config.groupMerge) ? e.group_id.toString() : e.sender.user_id}`)
await this.reply('已退出当前对话,该对话仍然保留。请@我进行聊天以开启新的对话', true)
} else if (use === 'bing' && (Config.toneStyle === 'Sydney' || Config.toneStyle === 'Custom')) {
let c = await redis.get(`CHATGPT:CONVERSATIONS_BING:${e.sender.user_id}`)
let c = await redis.get(`CHATGPT:CONVERSATIONS_BING:${(e.isGroup && Config.groupMerge) ? e.group_id.toString() : e.sender.user_id}`)
if (!c) {
await this.reply('当前没有开启对话', true)
return
} else {
await redis.del(`CHATGPT:CONVERSATIONS_BING:${e.sender.user_id}`)
await redis.del(`CHATGPT:CONVERSATIONS_BING:${(e.isGroup && Config.groupMerge) ? e.group_id.toString() : e.sender.user_id}`)
}
const conversation = {
store: new KeyvFile({ filename: 'cache.json' }),
@ -475,7 +489,18 @@ export class chatgpt extends plugin {
for (let i = 0; i < cs.length; i++) {
await redis.del(cs[i])
if (Config.debug) {
logger.info('delete slack conversation of qq: ' + cs[i])
logger.info('delete xh conversation of qq: ' + cs[i])
}
deleted++
}
break
}
case 'bard': {
let cs = await redis.keys('CHATGPT:CONVERSATIONS_BARD:*')
for (let i = 0; i < cs.length; i++) {
await redis.del(cs[i])
if (Config.debug) {
logger.info('delete bard conversation of qq: ' + cs[i])
}
deleted++
}
@ -1005,6 +1030,10 @@ export class chatgpt extends plugin {
key = `CHATGPT:CONVERSATIONS_XH:${(e.isGroup && Config.groupMerge) ? e.group_id.toString() : e.sender.user_id}`
break
}
case 'bard': {
key = `CHATGPT:CONVERSATIONS_BARD:${(e.isGroup && Config.groupMerge) ? e.group_id.toString() : e.sender.user_id}`
break
}
}
let ctime = new Date()
previousConversation = (key ? await redis.get(key) : null) || JSON.stringify({
@ -1038,6 +1067,12 @@ export class chatgpt extends plugin {
await e.reply([chatMessage.text, segment.image(`base64://${chatMessage.image}`)])
return false
}
// 处理星火和bard图片
if ((use === 'bard' || use === 'xh') && chatMessage?.images) {
chatMessage.images.forEach(async element => {
await e.reply([element.tag, segment.image(element.url)])
})
}
if (use === 'api' && !chatMessage) {
// 字数超限直接返回
return false
@ -1059,6 +1094,11 @@ export class chatgpt extends plugin {
} else if (chatMessage.id) {
previousConversation.parentMessageId = chatMessage.id
}
if (use === 'bard' && !chatMessage.error) {
previousConversation.parentMessageId = chatMessage.responseID
previousConversation.clientId = chatMessage.choiceID
previousConversation.invocationId = chatMessage._reqID
}
if (Config.debug) {
logger.info(chatMessage)
}
@ -1091,9 +1131,9 @@ export class chatgpt extends plugin {
response.length / 2 < endIndex
? [response.substring(startIndex), response.substring(0, startIndex)]
: [
response.substring(0, endIndex + 1),
response.substring(endIndex + 1)
]
response.substring(0, endIndex + 1),
response.substring(endIndex + 1)
]
const match = ttsArr[0].match(emotionReg)
response = ttsArr[1].replace(/\n/, '').trim()
if (match) {
@ -1647,7 +1687,6 @@ export class chatgpt extends plugin {
})
}
}
console.log(response)
// 处理内容生成的图片
if (response.details.imageTag) {
if (Config.debug) {
@ -1714,23 +1753,23 @@ export class chatgpt extends plugin {
bingTokens[badBingToken].State = '受限'
bingTokens[badBingToken].DisactivationTime = now
await redis.set('CHATGPT:BING_TOKENS', JSON.stringify(bingTokens))
// 不减次数
// 不减次数
} else if (message && typeof message === 'string' && message.indexOf('UnauthorizedRequest') > -1) {
// token过期了
// let bingTokens = JSON.parse(await redis.get('CHATGPT:BING_TOKENS'))
// const badBingToken = bingTokens.findIndex(element => element.Token === bingToken)
// // 可能是微软抽风,给三次机会
// if (bingTokens[badBingToken].exception) {
// if (bingTokens[badBingToken].exception <= 3) {
// bingTokens[badBingToken].exception += 1
// } else {
// bingTokens[badBingToken].exception = 0
// bingTokens[badBingToken].State = '过期'
// }
// } else {
// bingTokens[badBingToken].exception = 1
// }
// await redis.set('CHATGPT:BING_TOKENS', JSON.stringify(bingTokens))
// token过期了
// let bingTokens = JSON.parse(await redis.get('CHATGPT:BING_TOKENS'))
// const badBingToken = bingTokens.findIndex(element => element.Token === bingToken)
// // 可能是微软抽风,给三次机会
// if (bingTokens[badBingToken].exception) {
// if (bingTokens[badBingToken].exception <= 3) {
// bingTokens[badBingToken].exception += 1
// } else {
// bingTokens[badBingToken].exception = 0
// bingTokens[badBingToken].State = '过期'
// }
// } else {
// bingTokens[badBingToken].exception = 1
// }
// await redis.set('CHATGPT:BING_TOKENS', JSON.stringify(bingTokens))
logger.warn(`token${bingToken}疑似不存在或已过期,再试试`)
retry = retry - 0.1
} else {
@ -1845,16 +1884,71 @@ export class chatgpt extends plugin {
}
}
case 'xh': {
const cacheOptions = {
namespace: 'xh',
store: new KeyvFile({ filename: 'cache.json' })
}
const ssoSessionId = Config.xinghuoToken
if (!ssoSessionId) {
throw new Error('未绑定星火token请使用#chatgpt设置星火token命令绑定token。获取对话页面的ssoSessionId cookie值')
}
let client = new XinghuoClient({
ssoSessionId
ssoSessionId,
cache: cacheOptions
})
let response = await client.sendMessage(prompt, conversation?.conversationId)
// 获取图片资源
const image = await getImg(e)
let response = await client.sendMessage(prompt, conversation?.conversationId, image ? image[0] : undefined)
return response
}
case 'bard': {
// 处理cookie
const matchesPSID = /__Secure-1PSID=([^;]+)/.exec(Config.bardPsid)
const matchesPSIDTS = /__Secure-1PSIDTS=([^;]+)/.exec(Config.bardPsid)
const cookie = {
'__Secure-1PSID': matchesPSID[1],
'__Secure-1PSIDTS': matchesPSIDTS[1]
}
if (!matchesPSID[1] || !matchesPSIDTS[1]) {
throw new Error('未绑定bard')
}
// 处理图片
const image = await getImg(e)
let imageBuff
if (image) {
try {
let imgResponse = await fetch(image[0])
if (imgResponse.ok) {
imageBuff = await imgResponse.arrayBuffer()
}
} catch (error) {
logger.warn(`错误的图片链接${image[0]}`)
}
}
// 发送数据
let bot = new Bard(cookie, {
fetch: fetch,
bardURL: Config.bardForceUseReverse ? Config.bardReverseProxy : 'https://bard.google.com'
})
let chat = await bot.createChat(conversation?.conversationId ? {
conversationID: conversation.conversationId,
responseID: conversation.parentMessageId,
choiceID: conversation.clientId,
_reqID: conversation.invocationId
} : {})
let response = await chat.ask(prompt, {
image: imageBuff,
format: Bard.JSON
})
return {
conversationId: response.ids.conversationID,
responseID: response.ids.responseID,
choiceID: response.ids.choiceID,
_reqID: response.ids._reqID,
text: response.content,
images: response.images
}
}
default: {
let completionParams = {}
if (Config.model) {
@ -2206,6 +2300,105 @@ export class chatgpt extends plugin {
return true
}
async newxhBotConversation(e) {
let botId = e.msg.replace(/^#星火助手/, '').trim()
if (Config.xhmode != 'web') {
await e.reply('星火助手仅支持体验版使用', true)
return true
}
if (!botId) {
await e.reply('无效助手id', true)
} else {
const ssoSessionId = Config.xinghuoToken
if (!ssoSessionId) {
await e.reply(`未绑定星火token请使用#chatgpt设置星火token命令绑定token`, true)
return true
}
let client = new XinghuoClient({
ssoSessionId,
cache: null
})
try {
let chatId = await client.createChatList(botId)
let botInfoRes = await fetch(`https://xinghuo.xfyun.cn/iflygpt/bot/getBotInfo?chatId=${chatId.chatListId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Cookie: 'ssoSessionId=' + ssoSessionId + ';',
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/113.0.5672.69 Mobile/15E148 Safari/604.1',
}
})
if (botInfoRes.ok) {
let botInfo = await botInfoRes.json()
if (botInfo.flag) {
let ctime = new Date()
await redis.set(
`CHATGPT:CONVERSATIONS_XH:${(e.isGroup && Config.groupMerge) ? e.group_id.toString() : e.sender.user_id}`,
JSON.stringify({
sender: e.sender,
ctime,
utime: ctime,
num: 0,
conversation: {
conversationId: {
chatid: chatId.chatListId,
botid: botId
}
}
}),
Config.conversationPreserveTime > 0 ? { EX: Config.conversationPreserveTime } : {}
)
await e.reply(`成功创建助手对话\n助手名称:${botInfo.data.bot_name}\n助手描述:${botInfo.data.bot_desc}`, true)
} else {
await e.reply(`创建助手对话失败,${botInfo.desc}`, true)
}
} else {
await e.reply(`创建助手对话失败,服务器异常`, true)
}
} catch (error) {
await e.reply(`创建助手对话失败 ${error}`, true)
}
}
return true
}
async searchxhBot(e) {
let searchBot = e.msg.replace(/^#星火(搜索|查找)助手/, '').trim()
const ssoSessionId = Config.xinghuoToken
if (!ssoSessionId) {
await e.reply(`未绑定星火token请使用#chatgpt设置星火token命令绑定token`, true)
return true
}
const cacheresOption = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: 'ssoSessionId=' + ssoSessionId + ';',
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/113.0.5672.69 Mobile/15E148 Safari/604.1',
},
body: JSON.stringify({
botType: '',
pageIndex: 1,
pageSize: 45,
searchValue: searchBot
})
}
const searchBots = await fetch('https://xinghuo.xfyun.cn/iflygpt/bot/page', cacheresOption)
const bots = await searchBots.json()
if (Config.debug) {
logger.info(bots)
}
if (bots.code === 0) {
if (bots.data.pageList.length > 0) {
this.reply(await makeForwardMsg(this.e, bots.data.pageList.map(msg => `${msg.bot.botId} - ${msg.bot.botName}`)))
} else {
await e.reply(`未查到相关助手`, true)
}
} else {
await e.reply(`搜索助手失败`, true)
}
}
async emptyQueue(e) {
await redis.lTrim('CHATGPT:CHAT_QUEUE', 1, 0)
await this.reply('已清空当前等待队列')
@ -2354,7 +2547,7 @@ export class chatgpt extends plugin {
return await this.chatGPTApi.sendMessage(prompt, sendMessageOption)
}
async solveBingCaptcha (e) {
async solveBingCaptcha(e) {
try {
let id = e.bingCaptchaId
let regionId = e.regionId