Compare commits

...

844 commits
v2.3.3 ... v3

Author SHA1 Message Date
Copilot
00b24914dd
Fix initialization crash on cloud authentication failure (#821)
* Initial plan

* Fix cloud authentication failure handling to prevent initialization crash

Co-authored-by: ikechan8370 <21212372+ikechan8370@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ikechan8370 <21212372+ikechan8370@users.noreply.github.com>
2025-12-12 12:08:14 +08:00
ikechan8370
4b1a66b6bf docs: add better-sqlite3 hint 2025-11-08 16:14:23 +08:00
ikechan8370
b84bbcd55a
docs: Revise README for clarity and completeness
Updated README with plugin features, installation instructions, and usage guidelines.
2025-11-07 19:38:02 +08:00
ikechan8370
8bfce5402f
试验性的记忆功能 (#812)
* feat: memory basic

* fix: chaite ver

* fix: update prompt

* fix: memory cursor and extract prompt

* fix: memory retrieval bug

* fix: memory retrieval bug

* fix: one more attempt by codex

* fix: messages prompt error

* fix: one more time by codex

* fix: metrics by codex

* fix: memory forward

* fix: memory show update time
2025-11-07 16:40:26 +08:00
ikechan8370
db386ccaf2
Fix imageContent condition for base64 check 2025-08-26 22:24:05 +08:00
ikechan8370
8a924f91df
Update message.js 2025-08-26 22:13:10 +08:00
ikechan8370
dc1ab30b6a
Enhance image processing logic in message.js
Refactor image handling to support base64 and HTTP URLs.
2025-08-26 22:10:14 +08:00
ikechan8370
602e192bff fix: 整合多次思考 2025-07-04 12:25:21 +08:00
ikechan8370
185f163c9c fix: system 2025-04-29 23:09:00 +08:00
ikechan8370
a3c74f82db triggers 2025-04-28 16:18:27 +08:00
ikechan8370
c3b7127333 feat: file url 2025-04-16 20:38:41 +08:00
ikechan8370
85d61ea210 fix: 修改群聊提示词 2025-04-15 20:33:15 +08:00
ikechan8370
b30488bdb9 fix: 对话错误问题 2025-04-14 10:01:49 +08:00
ikechan8370
af28390a54 Merge branch 'v3' of github.com:ikechan8370/chatgpt-plugin into v3 2025-04-13 17:24:50 +08:00
ikechan8370
51765fcfa0 fix: tools group storage bug 2025-04-13 17:24:37 +08:00
ikechan8370
8c7cc3a2d2
Update README.md 2025-04-10 14:21:56 +08:00
ikechan8370
f4fb3dddd2 fix: config 重复保存 2025-04-10 13:33:39 +08:00
ikechan8370
6b36552c08 fix: config error 2025-04-10 12:56:48 +08:00
ikechan8370
3c83e270df fix: generateId 2025-04-10 12:15:01 +08:00
ikechan8370
64c77877ac fix: sqlite api 2025-04-10 12:09:23 +08:00
ikechan8370
0c602d6cb3 fix: history manager 2025-04-09 16:40:25 +08:00
ikechan8370
1788ee6d7d fix: finally 2025-04-09 16:31:17 +08:00
ikechan8370
fd197abb33 feat: use sqlite instead of lowdb 2025-04-09 16:27:21 +08:00
ikechan8370
9c41251164 fix 2025-04-07 20:02:24 +08:00
ikechan8370
7431814d1e fix: reg 2025-04-07 15:07:15 +08:00
ikechan8370
60f6ccb2d2 feat: 状态 2025-04-07 14:51:06 +08:00
ikechan8370
fd40992c78 fix: 导入 2025-04-07 14:07:32 +08:00
ikechan8370
14a84357ca fix: 导入 2025-04-07 14:07:10 +08:00
ikechan8370
3318ac04d8 fix: time 2025-04-07 00:33:35 +08:00
ikechan8370
7be0e61e14 fix: chaite ver 2025-04-05 23:07:02 +08:00
ikechan8370
5c1b74bfb1 fix: cloud wip 2025-04-05 23:06:24 +08:00
ikechan8370
f521e0ede8 fix: history storage初始化 2025-03-26 12:20:36 +08:00
ikechan8370
4216e64ed6 fix: history单独存 2025-03-26 12:08:40 +08:00
ikechan8370
fcbdf51eb8 fix: read old config 2025-03-26 12:01:00 +08:00
ikechan8370
7fe9673dce fix: debug 2025-03-25 20:40:23 +08:00
ikechan8370
089f6b6316 fix: 伪人错误记录历史的问题 2025-03-25 20:31:27 +08:00
ikechan8370
eb71222ed8 fix: merge 2025-03-24 12:52:30 +08:00
ikechan8370
c44e47be1c fix: bym conversation history 2025-03-24 12:51:57 +08:00
ikechan8370
127ba6d360 feat: update 2025-03-21 13:07:06 +08:00
ikechan8370
2401c5aed5 fix: 对话id 2025-03-21 12:50:11 +08:00
ikechan8370
d9b5d77d46 fix: 结束对话计算错误 2025-03-21 12:24:35 +08:00
ikechan8370
8d12cb7466 fix: 结束对话计算错误 2025-03-21 12:24:21 +08:00
ikechan8370
2fad551144 trim text 2025-03-21 12:23:02 +08:00
ikechan8370
89e265195d Merge branch 'v3' of github.com:ikechan8370/chatgpt-plugin into v3 2025-03-21 00:30:09 +08:00
ikechan8370
e1c4de4c10 fix: recall 2025-03-21 00:29:51 +08:00
ikechan8370
478080fe6b
fix: bym history 2025-03-21 00:19:30 +08:00
ikechan8370
66905640e4 fix: 很多功能 2025-03-20 22:43:39 +08:00
ikechan8370
a711ec13d7 fix: update chaite 2025-03-19 16:35:20 +08:00
ikechan8370
66281fc53e fix: add mimetype for claude 2025-03-18 22:49:20 +08:00
ikechan8370
f8591eba03 fix: 图片读取 2025-03-18 22:35:31 +08:00
ikechan8370
3c77da5373 fix: 调试设定和伪人 2025-03-18 22:11:31 +08:00
ikechan8370
efb5a8f174 fix: host port config 2025-03-17 21:34:16 +08:00
ikechan8370
9fcc25a726 feat: bym 2025-03-17 16:19:12 +08:00
ikechan8370
6997d1e024 fix: use latest chaite to enable dashboard 2025-03-16 22:30:17 +08:00
ikechan8370
6ff0453feb fix: lib version 2025-03-16 22:15:01 +08:00
ikechan8370
5046a4e0df fix: lib version 2025-03-16 22:14:27 +08:00
ikechan8370
eee1285e2f fix: 对接 2025-03-16 22:13:52 +08:00
ikechan8370
89ab58b3d7 fix: 管理功能(wip) 2025-03-15 17:45:34 +08:00
ikechan8370
d20974f25a fix: todo 2025-03-14 19:52:05 +08:00
ikechan8370
54806ee6fb fix: WIP 2025-03-13 15:54:32 +08:00
ikechan8370
116479e34e fix: config 2025-03-12 17:55:12 +08:00
ikechan8370
a16538f322 fix: chaite 2025-03-11 23:34:32 +08:00
ikechan8370
fbcf4e6c08 feat: chaite 初始化逻辑 2025-03-10 23:08:23 +08:00
ikechan8370
88312cdf38 fix: gitignore 2025-03-05 23:57:05 +08:00
ikechan8370
531986b2dc feat: init v3 2025-03-05 23:56:41 +08:00
ikechan8370
d6cb085c40 fix: 思考转发;claude上下文 2025-02-27 20:19:38 +08:00
ikechan8370
cf31d40cf4 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2025-02-26 22:23:24 +08:00
ikechan8370
7fcf0c6b58 fix: claude max token 2025-02-26 22:20:53 +08:00
ikechan8370
31a73e428a
Update README.md 2025-02-24 20:47:06 +08:00
Etgpao
47016aeaa1
Update SendMusicTool.js (#745)
适配napcat
2025-02-21 14:08:58 +08:00
ikechan8370
7bf1c84989 fix: post processors 2025-02-19 13:22:53 +08:00
ikechan8370
2ab56e15a7 fix: post processors 2025-02-19 13:21:01 +08:00
ikechan8370
5add41c982 fix: post processors 2025-02-19 13:10:59 +08:00
ikechan8370
20195ecfdf fix: 发图工具的小bug 2025-02-18 00:09:41 +08:00
ikechan8370
bde81c0a17 fix: MALFORMED_FUNCTION_CALL 2025-02-17 23:54:08 +08:00
ikechan8370
b9ed12adb7 fix: 设定列表太长发不出来的问题 2025-02-17 23:46:44 +08:00
ikechan8370
a97f01b9d3 fix: guoba 2025-02-17 23:00:06 +08:00
ikechan8370
0fae49d5d1 fix: adjust website tools; trim gemini intermediate response 2025-02-17 22:45:39 +08:00
ikechan8370
41be6befec fix: github tool adjustment 2025-02-17 13:24:30 +08:00
ikechan8370
0ad0e2d237 feat: add github tool 2025-02-17 12:41:51 +08:00
ikechan8370
84e7e6b859 fix: adjust serp tool 2025-02-17 11:55:42 +08:00
ikechan8370
95e776b334 fix: 死循环 2025-02-17 02:23:50 +08:00
ikechan8370
3b58397a16 fix: 锅巴 2025-02-17 02:10:59 +08:00
ikechan8370
d29bfb0bc2 fix: 增加强制工具关键词 看你还不听话 2025-02-17 02:09:51 +08:00
ikechan8370
b486b45f44 fix: adjust tools 2025-02-17 01:56:36 +08:00
ikechan8370
d96349dde3 fix: 增加智能模式私聊开关 2025-02-16 22:21:31 +08:00
ikechan8370
777279e410 fix: 工具调整 2025-02-16 21:43:23 +08:00
ikechan8370
08afc95f06 fix: 修复gemini禁言和提出对非管理员不生效的问题 2025-02-16 21:29:47 +08:00
ikechan8370
fcca28de37 fix: 修复前几天支持multiple tools导致的gemini搜了不发的问题 2025-02-16 20:59:26 +08:00
ikechan8370
213818b635 fix: 修复搜索为空 2025-02-16 20:46:09 +08:00
ikechan8370
f619035e52 fix: 伪人限制开启上下文,不然笨死了 2025-02-15 23:42:28 +08:00
ikechan8370
c3eb8ac5db fix: 聊天记录bug;删除日志 2025-02-15 23:39:45 +08:00
ikechan8370
9930e53a03 fix: 聊天记录重复的问题 2025-02-15 23:28:14 +08:00
ikechan8370
afa456f044 fix: 错误过滤非文本消息的问题 2025-02-15 23:08:03 +08:00
ikechan8370
1911e5ca4b fix: 发癫一样的给bym私聊狂发图 2025-02-15 20:26:24 +08:00
ikechan8370
98d129517a fix: error when gemini multiple functionCall in one response 2025-02-15 20:24:04 +08:00
ikechan8370
69ff552dc9 fix: 图片分开发送避免失败 2025-02-15 19:33:16 +08:00
ikechan8370
870eba51d2 fix: 智障吧我是 2025-02-15 19:20:52 +08:00
ikechan8370
83c481a4bc Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2025-02-15 19:14:23 +08:00
ikechan8370
9f521064a1 fix: 搜图工具增加yandex 2025-02-15 19:14:17 +08:00
ikechan8370
88360ecc42 fix: 修复上下文聊天大于20时记录顺序错误的问题 2025-02-14 00:14:23 +08:00
ikechan8370
2ad77d8112 fix: 工具私聊 2025-02-12 15:43:37 +08:00
ikechan8370
8417008c38 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2025-02-12 15:25:53 +08:00
ikechan8370
4a3090c6f9 fix: #760 2025-02-12 15:25:47 +08:00
ikechan8370
6d9c842a8f
fix: bym也走智能模式配置 2025-02-11 23:16:51 +08:00
ikechan8370
b95bacc7e8 fix: 看配置 2025-02-10 17:19:14 +08:00
ikechan8370
d957025fa8 fix: 看配置 2025-02-10 17:15:48 +08:00
ikechan8370
8249acaf08 fix: max token 2025-02-10 17:11:41 +08:00
misaka20002
dcc1a4ebd6
feat: 伪人禁用群 (#758) 2025-02-07 22:14:09 +08:00
ikechan8370
916e1082d7 fix: 修改刷新copilot token间隔 2025-02-07 00:02:42 +08:00
ikechan8370
c1dd406b62 fix: task format 2025-02-06 23:38:40 +08:00
ikechan8370
e67a145635 fix: bing自动刷新;<EMPTY>匹配错误 2025-02-06 21:46:02 +08:00
ikechan8370
f9a6fafb9e fix: gemini empty text 2025-02-05 15:51:37 +08:00
ikechan8370
d656313811 fix: update refreshToken 2025-02-05 15:37:32 +08:00
ikechan8370
ce4504e251 fix: refresh bing token 2025-02-05 12:14:42 +08:00
ikechan8370
d7d4acf382 fix: 过码第二遍才生效的问题 2025-02-04 23:25:54 +08:00
ikechan8370
243331aa2e fix: 复活Copilot但有代价 2025-02-04 23:11:07 +08:00
ikechan8370
dcae426cfa fix: increase max token for api mode 2025-02-04 17:42:41 +08:00
ikechan8370
1625401f14 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2025-02-04 12:14:07 +08:00
ikechan8370
e224272012 fix: gemini system cannot be empty 2025-02-04 12:13:58 +08:00
ikechan8370
17f41dcdeb
Update README.md 2025-02-03 20:47:30 +08:00
ikechan8370
bbba9bc872 fix: 微调gemini识图,删除本地缓存 2025-02-03 20:11:25 +08:00
ikechan8370
f05da98d37 feat: add switch for thinking content forward 2025-02-03 18:36:47 +08:00
ikechan8370
43fb604742 fix: xh bym 2025-02-03 00:19:18 +08:00
ikechan8370
6f3679b70d fix: add ^#chatgpt(伪人|bym)切换 2025-02-03 00:13:46 +08:00
ikechan8370
69ab6dcd28 feat: bym.js support multiple models 2025-02-03 00:07:26 +08:00
ikechan8370
f7030e8427 fix: adjust bym.js text filter 2025-01-31 23:43:55 +08:00
ikechan8370
acb9e76b0e fix: use system_instruction instead of user for gemini client 2025-01-31 22:02:10 +08:00
ikechan8370
65bb1539e2 fix: content和reasoning_content是同时出现的 2025-01-30 11:48:35 +08:00
ikechan8370
6442e371ee fix: 遗漏提交 2025-01-30 11:43:07 +08:00
ikechan8370
4b9dd0395d fix: 非流模式的思考转发 2025-01-30 11:42:51 +08:00
ikechan8370
3cd664ff53 feat: 转发thinking的内容 2025-01-30 00:36:58 +08:00
ikechan8370
5e4d921002
fix: update prompt management 2025-01-27 18:40:08 +08:00
ikechan8370
994a83ac4a Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2025-01-08 20:40:04 +08:00
ikechan8370
ced7a5a01f fix: gemini filter 2025-01-08 20:39:36 +08:00
misaka20002
7974c6a1c9
feat: 轮询geminiKeys,用英文逗号隔开 (#744) 2025-01-04 14:49:52 +08:00
ikechan8370
25520ba9fe fix: text split error 2025-01-03 14:27:00 +08:00
ikechan8370
43faf96cfe fix: filter empty message 2025-01-02 21:40:21 +08:00
ikechan8370
802776cfa1 fix: filter empty message to avoid -60 2025-01-02 21:05:23 +08:00
ikechan8370
6ccf0fed7f fix: filter empty message to avoid -60 2025-01-02 21:00:40 +08:00
ikechan8370
75cf2e3523 fix: filter empty 2025-01-02 20:59:07 +08:00
ikechan8370
cce3f2c28c fix: filter empty 2025-01-02 20:56:20 +08:00
ikechan8370
314c60d0ae fix: bym optimizing 2025-01-02 20:51:45 +08:00
syfantasy
1c34ecbb83
feat: add bymFuckList Configuration (#737)
* feat: add bymFuckList

* feat: geminikey load balancing

* add: console.log()

* fix:  whole key

* fix:  whole key

* feat: geminikey load balancing
2025-01-02 16:06:30 +08:00
ikechan8370
5692af692b fix: bym qq 2024-12-31 13:06:06 +08:00
ikechan8370
1149f34070 fix: tool permission 2024-12-31 13:02:18 +08:00
ikechan8370
f6ce6dcec5 fix: bym 又发现了bym的bug 2024-12-29 20:40:56 +08:00
ikechan8370
11fb6f5281 fix: try to fix #732 2024-12-29 20:34:12 +08:00
Ethan
5f2b88851f
修复发送图片 (#729) 2024-12-29 20:32:46 +08:00
ikechan8370
027ff17b13 fix: 修复bym发现的bymbug 2024-12-29 20:24:46 +08:00
ikechan8370
221cf4082d fix: gemini function call 2024-12-29 20:11:32 +08:00
ikechan8370
26444df2a2
Update bym.js (#735)
* feat: new bing (WIP)

* fix: update CopilotAIClient.js

* fix: gemini强制调用tool;real at

* feat: add bym support
2024-12-29 19:57:55 +08:00
ikechan8370
5f6c4e5abb feat: support search for gemini2: #chatgpt开启gemini搜索 #chatgpt开启代码执行 暂时不可并存 2024-12-12 20:31:39 +08:00
ikechan8370
8fc2ca5621
fix: revert openai version 2024-11-19 23:03:55 +08:00
ikechan8370
dc751750f4 fix: 用AUTO作为gemini工具默认选项 2024-11-19 11:08:33 +08:00
ikechan8370
f6e054b7ef fix: bot一直骂我 2024-11-19 10:55:45 +08:00
ikechan8370
df715e22a2 fix: merge (maybe broken?) 2024-11-19 10:35:38 +08:00
ikechan8370
a77a0e430f fix: WIP openai rewrite 2024-11-19 10:32:10 +08:00
ikechan8370
30f9c82d73 fix: gemini tool optional 2024-11-18 12:02:41 +08:00
青青
2b9734c641
兼容trss (#723)
Co-authored-by: Jin1c on imini <Jin0x31c@gmail.com>
2024-10-29 16:01:55 +08:00
ikechan8370
aa2ac7b5d3 fix: add example 2024-10-11 23:07:09 +08:00
ikechan8370
479028584e fix: move files 2024-10-11 23:04:54 +08:00
ikechan8370
d08e9e4102 feat: 自定义后处理器 2024-10-11 22:28:14 +08:00
ikechan8370
f0a17dc422 fix: #713 2024-10-11 22:15:05 +08:00
ikechan8370
3822da62b0
Update README.md 2024-10-11 21:43:04 +08:00
ikechan8370
b87bf77728
fix: try to fix openai version 2024-08-06 11:20:17 +08:00
misaka20002
beaec147b5
gemini智能模式下主人可使用bot管理员禁言权限 (#708) 2024-08-03 21:13:01 +08:00
ikechan8370
ac304e0ed3 fix: gemini禁言越权问题 2024-08-03 13:24:01 +08:00
ikechan8370
7c2961cdcd fix: text null 2024-07-29 17:25:31 +08:00
ikechan8370
1682b715fd fix: gemini mode text & FunctionCall 2024-07-29 17:24:02 +08:00
ikechan8370
e6af4083c2 fix: 修复Gemini的图片和工具支持 2024-07-29 16:49:40 +08:00
憨憨
1fad082da6
fix: 识图模型报错 2024-07-22 15:23:19 +08:00
ikechan8370
49aade9ac6 fix: xh 4.0 2024-06-27 15:31:02 +08:00
ikechan8370
cc90e38ba8 fix: xh 4.0 2024-06-27 15:25:04 +08:00
ikechan8370
b1eff1700e fix: xh 4.0 2024-06-27 14:53:05 +08:00
ikechan8370
500b743390
fix: remove adapter check for tokenizer 2024-06-13 11:42:21 +08:00
ikechan8370
5c7c430da6
fix: remove adapter check for getImg 2024-06-13 11:40:31 +08:00
ikechan8370
01425103f4 fix: fallback gpt4-o 2024-05-16 18:50:37 +08:00
ikechan8370
5aa90788c2 fix: add api3 timeout option 2024-05-15 20:09:18 +08:00
ikechan8370
21485df0aa fix: api3 gpt-4o 2024-05-15 19:56:51 +08:00
ikechan8370
d82320d04c fix: remove code about queue 2024-05-15 18:24:12 +08:00
ikechan8370
bb87169454 fix: #chatgpt删除token 2024-05-15 18:12:01 +08:00
ikechan8370
08e78209a0 fix: symbol error 2024-05-15 17:59:34 +08:00
ikechan8370
72b6dcf54d fix: message id 2024-05-15 17:45:48 +08:00
ikechan8370
1f80758491 feat: add synthesis for api3 2024-05-15 17:24:50 +08:00
ikechan8370
b76d33d938 fix: add retry for api3 2024-05-14 23:52:26 +08:00
ikechan8370
a507c85cf8
Update message.js 2024-05-14 23:02:36 +08:00
ikechan8370
6f7bb4f7fd
fix: allow empty api3 token 2024-05-14 22:59:27 +08:00
ikechan8370
21a15c58ea
fix: allow empty api3 token 2024-05-14 22:58:15 +08:00
HalcyonAlcedo
e70f0a79f4
Merge pull request #695 from HalcyonAlcedo/v2
更新歌词匹配
2024-05-09 22:31:01 +08:00
zyc404
adcbcf1f40 更新歌词匹配 2024-05-09 22:30:23 +08:00
HalcyonAlcedo
3fb0d7d114
Merge pull request #694 from HalcyonAlcedo/v2
优化歌曲消息匹配,适配更多模型支持生成歌曲
2024-05-09 22:16:52 +08:00
zyc404
7288e2b845 优化歌曲消息匹配,适配更多模型支持生成歌曲 2024-05-09 22:09:51 +08:00
HalcyonAlcedo
f789556a90
Merge pull request #693 from HalcyonAlcedo/v2
将suno生成应用于更多模型
2024-05-08 16:38:44 +08:00
zyc404
554f6a69f3 添加后台对话模式选项 2024-05-08 16:35:51 +08:00
zyc404
8efcce45a0 去除bard 2024-05-08 15:42:35 +08:00
zyc404
d111d2625e 修改suno伪造生成策略,支持更多模型调用 2024-05-08 15:32:49 +08:00
zyc404
123e5304a7 对原始数据进行编辑 2024-05-08 13:26:42 +08:00
HalcyonAlcedo
68b243670c
Merge pull request #691 from HalcyonAlcedo/v2
增加视频下载延迟
2024-05-08 00:25:41 +08:00
zyc404
f66b4a8548 增加视频下载延迟 2024-05-08 00:23:42 +08:00
HalcyonAlcedo
07831d6108
Merge pull request #690 from HalcyonAlcedo/v2
增强bing suno功能
2024-05-07 23:21:04 +08:00
zyc404
8bd58cf429 增加suno生成等待时间,修复下载视频参数错误 2024-05-07 23:18:32 +08:00
zyc404
b20a3db006 更多样的bing suno生成 2024-05-07 23:02:18 +08:00
HalcyonAlcedo
ea7ea93d33
Merge pull request #689 from HalcyonAlcedo/v2
添加第三方suno支持
2024-05-07 14:44:43 +08:00
zyc404
991c63bb26 修复部分适配器不支持pickMember的问题 2024-05-07 14:41:05 +08:00
zyc404
f8f5f8f83a 添加bing第三方suno生成支持 2024-05-07 14:33:52 +08:00
HalcyonAlcedo
1e4764fd14
Merge pull request #688 from HalcyonAlcedo/v2
添加对bing suno插件的支持
2024-05-07 13:52:03 +08:00
zyc404
ec47a4d9b0 添加对bing suno插件的支持 2024-05-07 13:50:06 +08:00
HalcyonAlcedo
a9ef38cbde
Merge pull request #686 from HalcyonAlcedo/v2
部分修复bing问题
2024-05-06 22:59:11 +08:00
zyc404
33e04c1c24 修复bing图片生成请求(绘图接口仍有问题) 2024-05-06 22:47:20 +08:00
zyc404
8dab6fd0b5 修复bing图片识别问题 2024-05-06 20:28:42 +08:00
HalcyonAlcedo
03e3094c15
更新后台面板 (#684)
* fix: 修复星火api上下文

* 将无星火ck的情况降低为warn

* feat: 添加星火设定自定义代码功能

* 修复星火api模式的一些问题

* 修复导出配置问题

* feat:添加工具箱快捷登录接口

* 添加工具箱快捷登录指令

* 阻止群聊使用快捷登录

* 添加Azure配置支持,修复重复的配置项冲突

* 移除旧版本渲染和新版本帮助

* 添加工具箱

* 更新工具箱替换原有后台

* 更新工具箱适配代码

* 后台适配Trss

* 修复trss不支持sendPrivateMsg的问题

* 优化路由

* 修复路由

* 适配其他uin

* 添加bing第三方绘图

* 修复bing绘图第三方调用错误

* 添加bing第三方绘图采样配置

* 修复错误

* 添加bing第三方绘图图片大小配置

* 修复视图错误

* 使用ap替换第三方绘图

* 适配trss

* server 适配trss

* 修复错误的后台版本更新

* 添加锅巴用户数据

* 修复server初始化消息错误

* 添加锅巴插件适配

* 更新后台页面

* 添加锅巴代理接口

* 优化锅巴接口代理

* 修复锅巴代理参数

* 删除调试信息

* 修复headers

* 更新后台锅巴插件支持

* 适配星火v3

* 适配星火v3

* 修复星火domain错误

* 修复更新后trss无法快捷登陆面板问题

* 奇怪的错误,忽略提示不影响使用

* 添加后台配置项

* 添加后台星火v3.5模式选项

* 添加后台缺少的部分配置项

* 增加后台对缺少的锅巴配置自动读取,将后台登陆信息添加到redis

* 后台适配trss,更新web

* 更新后台
2024-05-05 23:57:40 +08:00
zyc404
eb2618b141 更新后台 2024-05-05 21:25:38 +08:00
zyc404
f3fb9aa0ee 后台适配trss,更新web 2024-05-05 15:12:47 +08:00
HalcyonAlcedo
b431794497
对后台更新 (#683)
* fix: 修复星火api上下文

* 将无星火ck的情况降低为warn

* feat: 添加星火设定自定义代码功能

* 修复星火api模式的一些问题

* 修复导出配置问题

* feat:添加工具箱快捷登录接口

* 添加工具箱快捷登录指令

* 阻止群聊使用快捷登录

* 添加Azure配置支持,修复重复的配置项冲突

* 移除旧版本渲染和新版本帮助

* 添加工具箱

* 更新工具箱替换原有后台

* 更新工具箱适配代码

* 后台适配Trss

* 修复trss不支持sendPrivateMsg的问题

* 优化路由

* 修复路由

* 适配其他uin

* 添加bing第三方绘图

* 修复bing绘图第三方调用错误

* 添加bing第三方绘图采样配置

* 修复错误

* 添加bing第三方绘图图片大小配置

* 修复视图错误

* 使用ap替换第三方绘图

* 适配trss

* server 适配trss

* 修复错误的后台版本更新

* 添加锅巴用户数据

* 修复server初始化消息错误

* 添加锅巴插件适配

* 更新后台页面

* 添加锅巴代理接口

* 优化锅巴接口代理

* 修复锅巴代理参数

* 删除调试信息

* 修复headers

* 更新后台锅巴插件支持

* 适配星火v3

* 适配星火v3

* 修复星火domain错误

* 修复更新后trss无法快捷登陆面板问题

* 奇怪的错误,忽略提示不影响使用

* 添加后台配置项

* 添加后台星火v3.5模式选项

* 添加后台缺少的部分配置项

* 增加后台对缺少的锅巴配置自动读取,将后台登陆信息添加到redis
2024-05-05 14:09:39 +08:00
zyc404
adc2931351 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2024-05-05 00:40:59 +08:00
zyc404
369dbd31c3 增加后台对缺少的锅巴配置自动读取,将后台登陆信息添加到redis 2024-05-05 00:40:10 +08:00
HUvz
7bbe1a9db1
fix: waitForTimeout is not a function (#674)
* fix:issue #673

* fix: 更换延迟函数

* fix: goto改用waitUntil
2024-05-01 11:36:44 +08:00
zyc404
5acf874e0b 添加后台缺少的部分配置项 2024-04-25 16:21:02 +08:00
zyc404
c2f4b26904 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2024-04-25 15:49:43 +08:00
ikechan8370
c622f7eba5 fix: add retry for suno video download 2024-04-03 14:25:45 +08:00
ikechan8370
5762485193
fix: 微调样式 2024-03-29 16:49:00 +08:00
zyc404
b0c6cadbc8 添加后台星火v3.5模式选项 2024-03-28 13:47:32 +08:00
zyc404
f63af3349a Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2024-03-28 13:43:41 +08:00
ikechan8370
f68e7cf5ce fix: 优化识图报错 2024-03-21 00:15:06 +08:00
ikechan8370
7d39af6a8c fix: add support for claude vison 2024-03-16 14:49:54 +08:00
ikechan8370
81a45b1333 fix: reply 2024-03-16 00:42:06 +08:00
ikechan8370
4eaf218d66 feat: add #识图 2024-03-16 00:36:27 +08:00
ikechan8370
a4d07b9d46 fix: 增加均衡模式 2024-03-15 10:52:21 +08:00
ikechan8370
b822e49d9a fix: 流模式带多余undefined的问题 2024-03-14 20:52:57 +08:00
ikechan8370
2ca27dae8d Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2024-03-14 14:46:22 +08:00
ikechan8370
a539b26e8e fix: remove strange makeforward 2024-03-14 14:45:28 +08:00
ikechan8370
267f67bb6c
fix: add claude-3-haiku-20240307 2024-03-14 12:51:55 +08:00
ikechan8370
868255893f fix: 指令添加key的提示 2024-03-13 18:29:51 +08:00
ikechan8370
3b5a26ce62 feat: simple random load balance for claude api key 2024-03-13 18:27:55 +08:00
ikechan8370
7d83c34e98 fix: guoba typo 2024-03-13 15:07:54 +08:00
ikechan8370
5a6990ee86 fix: guoba typo 2024-03-13 15:05:10 +08:00
ikechan8370
1d42dc6f31 feat: add example turns for bing and prompts 2024-03-13 15:00:21 +08:00
ikechan8370
36f0dbd94f fix: bing full ck 2024-03-12 21:10:08 +08:00
ikechan8370
bbe70e3945 fix: qwen contect 2024-03-12 18:35:24 +08:00
ikechan8370
20a1a7dcdf fix: qwen contect 2024-03-12 18:30:09 +08:00
ikechan8370
b221098c37 fix: refactor qwen mode 2024-03-12 18:18:06 +08:00
ikechan8370
32af7b9a74 fix: 生成较长时suno token过期重新刷新 2024-03-11 13:43:23 +08:00
ikechan8370
d004699e21 fix: 生成较长时suno token过期重新刷新 2024-03-11 13:35:00 +08:00
ikechan8370
e47ec3cd5c fix: disable picture mode under md mode 2024-03-10 17:34:45 +08:00
ikechan8370
fd2d976686 cherry-pick: 1 2024-03-10 17:34:33 +08:00
阿信
8e73a28dae
修改package.json (#662)
* Modified package.json

* Update package.json

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2024-03-10 14:36:36 +08:00
ikechan8370
bd7aac0517 fix: remove useless thing 2024-03-09 23:37:47 +08:00
ikechan8370
5c544a5ca7 fix: version 2024-03-08 15:20:57 +08:00
ikechan8370
56be26e001 fix: md claude model 2024-03-08 14:47:20 +08:00
ikechan8370
3be095785a fix: md claude model 2024-03-08 14:46:09 +08:00
ikechan8370
b4e017a69d fix: button 2024-03-08 14:44:42 +08:00
ikechan8370
f0c284cc2f fix: copilot乱写的bug 2024-03-08 14:41:41 +08:00
ikechan8370
79ab6cbd40 feat: support claude api fix #659 2024-03-08 14:38:39 +08:00
ikechan8370
8b2493a4bf
fix: replace stream with file 2024-03-07 10:49:22 +08:00
ikechan8370
eef4254e00
fix: typo OpenAI 2024-03-07 00:29:27 +08:00
ikechan8370
4581db1b8c
fix: error 2024-03-06 23:55:56 +08:00
ikechan8370
03068f5101
fix: try to fix no handler version 2024-03-06 23:09:11 +08:00
ikechan8370
87af85671e
fix: syntax error 2024-03-06 19:11:26 +08:00
ikechan8370
6b58def252
fix: remove md conditions 2024-03-06 18:15:51 +08:00
ikechan8370
1e1584b6ff fix: screenshot command 2024-03-05 14:30:30 +08:00
ikechan8370
cb3e57bea3
feat: experimental markdown support (#658)
* feat: test button

* fix: enter

* fix: bing suggested

* fix: bing suggested

* fix: bing suggested

* fix: button under icqq

* fix: 删除suno心跳

* fix: add default md handler

* fix: duplicate this

* fix: add a button

* Update md.js

* Update md.js

* fix: api stream

* fix: claude.ai

* fix: md enhancement

* fix: optional buttons

* fix: mode name

* fix: ignore md while not enable md
2024-03-05 14:12:50 +08:00
ikechan8370
58e6201e6e fix: replace getMemberMap with gml 2024-02-28 16:39:57 +08:00
ikechan8370
9c73c99b65 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2024-02-28 16:36:38 +08:00
ikechan8370
cf7da0d2c5 fix: replace getMemberMap with gml 2024-02-28 16:36:25 +08:00
ikechan8370
bf75c002c0 fix: remove long translation result forward 2024-02-24 16:52:01 +08:00
ikechan8370
f1b950ce58 fix: 笔误 2024-02-23 00:35:49 +08:00
ikechan8370
edafe602c1 fix: 反馈 2024-02-23 00:34:11 +08:00
ikechan8370
4886042e3c fix: 增加指令切换翻译源 2024-02-23 00:32:36 +08:00
ikechan8370
35ad437df2 fix: 语种问题 2024-02-23 00:25:32 +08:00
ikechan8370
e1d40ba009 fix: 添加基于LLM的翻译 2024-02-23 00:18:04 +08:00
ikechan8370
e5e85621d9 fix: claude2 response format 2024-02-22 13:04:19 +08:00
ikechan8370
9ef463fddc fix: claude2 url error 2024-02-22 12:40:47 +08:00
ikechan8370
ec2e123e72 fix: claude2 2024-02-22 12:38:33 +08:00
ikechan8370
0cdd2be29a fix: 使用icqq发送视频 2024-02-22 12:21:23 +08:00
ikechan8370
4cbca97c56 fix: 减少重试次数 2024-02-21 19:14:23 +08:00
ikechan8370
3561f7c99d fix: query song add fallback 2024-02-21 15:09:12 +08:00
ikechan8370
7635781695 fix: 余额不足提示 2024-02-21 15:03:12 +08:00
ikechan8370
324f447401 fix: 死循环 2024-02-21 14:58:18 +08:00
ikechan8370
6560cec87e fix: 文本乱了 2024-02-21 14:52:17 +08:00
ikechan8370
76caf5d040 fix: 邮箱打码 2024-02-21 14:50:44 +08:00
ikechan8370
c46c8fe458 fix: 循环 2024-02-21 14:44:59 +08:00
ikechan8370
ba3422cd10 fix: suno余额查询:#suno余额 2024-02-21 14:43:00 +08:00
ikechan8370
eea0748de7 feat: 支持suno:#suno+prompt#创作歌曲+prompt 2024-02-21 14:38:13 +08:00
ikechan8370
63edc9403c fix: 兼容性问题 2024-02-19 21:28:14 +08:00
ikechan8370
2c9008ea56 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2024-02-18 21:38:14 +08:00
ikechan8370
76ecabe104 fix: 小重构必应 2024-02-18 21:38:06 +08:00
hanhan258
f04d0cdc6b
Merge pull request #649 from hanhan258/v2
fix:dalle3,调用模型错误
2024-02-18 14:27:03 +08:00
hanhan258
c917688478 fix:dalle3 2024-02-18 14:25:00 +08:00
hanhan258
b4eba8096e
Merge pull request #647 from hanhan258/v2
feat:dalle3
2024-02-17 21:14:20 +08:00
hanhan258
74a0b7ddbc feat:dalle3 2024-02-17 21:12:49 +08:00
hanhan258
b3865d18c7
Merge pull request #644 from hanhan258/v2
feat:指令查看当前部分配置,api流开关
2024-02-15 16:04:57 +08:00
hanhan258
a32eb61f84 feat:指令查看当前部分配置,api流开关 2024-02-15 16:04:11 +08:00
ikechan8370
389940085a fix: xh设定 2024-02-01 22:51:58 +08:00
ikechan8370
8cc7105f2d fix: xh prompt turn to system role 2024-02-01 22:50:16 +08:00
ikechan8370
8ec1ee4c1e fix: xh 3.5 2024-02-01 22:42:42 +08:00
ikechan8370
fc8bace2c5 fix: xh 3.5 2024-02-01 22:25:16 +08:00
ikechan8370
ba83d6c31d fix: #638 2024-02-01 22:21:37 +08:00
hanhan258
4f10fcbeb1
Merge pull request #637 from hanhan258/v2
feat:修复qwen是gemini,增加双子星、智谱结束(全部)对话
2024-01-21 20:21:28 +08:00
hanhan258
5acd7cc023 feat:修复qwen是gemini,增加双子星、智谱结束(全部)对话 2024-01-21 20:07:53 +08:00
ikechan8370
966ea2d016 fix: add timeout for https 2024-01-17 13:26:13 +08:00
ikechan8370
006abb3257 fix: first msg no content 2024-01-17 13:17:21 +08:00
ikechan8370
37d1d04de6 fix: content parts 2024-01-17 13:10:28 +08:00
ikechan8370
c69358cd80 feat: support chatglm.cn 2024-01-17 13:06:59 +08:00
ikechan8370
8bdf9a3b6d feat: 适配copilot pro账户的gpt4-turbo选项 2024-01-16 20:32:22 +08:00
zyc404
9229be62cb Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2024-01-04 10:28:55 +08:00
ikechan8370
3709166b2d fix #633 2024-01-02 20:43:07 +08:00
ikechan8370
5e41205728 fix: 清理代码 2024-01-01 20:01:01 +08:00
misaka20002
35c2788463
修复 #chatgpt(本群)?(群\\d+)?(闭嘴|关机|休眠|下班) 与 #chatgpt关闭画图 正则表达式冲突 (#632) 2023-12-31 11:28:54 +08:00
ikechan8370
a00956ef43 feat: #chatgpt必应禁用搜索 #chatgpt必应开启搜索 2023-12-28 13:03:57 +08:00
HalcyonAlcedo
fc4eaf8dcf
添加Gemini配置项 (#626) 2023-12-17 01:04:46 +08:00
zyc404
3eaa331dd0 添加后台配置项 2023-12-16 20:18:38 +08:00
zyc404
5c52962737 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-12-16 20:05:59 +08:00
ikechan8370
22dcb0405b Note: The gemini-pro-vision model (for text-and-image input) is not yet optimized for multi-turn conversations. Make sure to use gemini-pro and text-only input for chat use cases. 2023-12-15 20:26:05 +08:00
ikechan8370
4dc5d6fe77 fix: 权限和角色问题导致的工具调用失败 2023-12-15 18:08:03 +08:00
ikechan8370
0ac70a325f
fix 2023-12-15 01:53:02 +08:00
ikechan8370
39ef573dd3 fix: guoba 2023-12-15 01:14:05 +08:00
ikechan8370
bbe769f1aa fix: 实现Gemini客户端取代官方版本 2023-12-15 00:41:42 +08:00
ikechan8370
6769e9d3f0 fix: 增加#chatgpt修补Gemini 以暂时解决google库不支持反代的问题 2023-12-14 18:27:40 +08:00
ikechan8370
3aefa40920 fix: update topP 2023-12-14 18:02:19 +08:00
ikechan8370
8e846d9c9f fix: add package patch 2023-12-14 17:44:15 +08:00
ikechan8370
315b16ac0d fix: 添加依赖提示 2023-12-14 17:31:40 +08:00
ikechan8370
220525fbbd feat: 支持GeminiPro模型 2023-12-14 17:25:55 +08:00
ikechan8370
ac0aa7d02d fix: adjust error hint of blocked prompt 2023-12-13 00:25:56 +08:00
hanhan258
6f0a79559b
feat:结束其他模式对话 (#622)
* fix: 修正fastify版本为4.18.0

* fix: 修正fastify版本为4.18.0

* fix:修复正则

* feat:指令查看模型列表,指令设置API模型、API反代、星火版本

* feat:结束其他模式对话
2023-12-12 20:34:05 +08:00
ikechan8370
d00ab5df5f fix: https error 2023-12-12 20:12:30 +08:00
ikechan8370
ca34338b72 fix: merge 2023-12-12 19:50:15 +08:00
ikechan8370
3f98d480de fix: 优化必应绘图逻辑 2023-12-12 19:48:03 +08:00
ikechan8370
16d9462e7c fix: 必应画图被屏蔽的提示词 2023-12-12 13:58:16 +08:00
ikechan8370
e5d6a415e8 fix: 修改必应绘图失败提示词避免ap画出来 2023-12-12 13:25:45 +08:00
ikechan8370
fd0d0ff5db fix: 修复必应画图多余的svg 2023-12-12 13:15:05 +08:00
ikechan8370
5f23d97bb3 fix: 修复必应画图多余的svg 2023-12-12 13:10:31 +08:00
ikechan8370
2f1c3317f4
Update README.md 2023-12-11 17:02:11 +08:00
ikechan8370
b8eaffe930 fix: query user info tools 2023-12-11 01:02:31 +08:00
ikechan8370
e61d4ff3fa fix: 修复和优化群聊文件读取逻辑 2023-12-11 00:46:38 +08:00
ikechan8370
d254163fa7 fix: bug fix 2023-12-10 23:16:40 +08:00
ikechan8370
699d2c8d27 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-12-10 23:13:37 +08:00
ikechan8370
247f3e15d0 fix: 上下文、文件、ocr等进一步适配shamrock 2023-12-10 23:08:10 +08:00
HalcyonAlcedo
ae23e6d7f5
修复trss无法快速登陆后台的问题 (#620)
* fix: 修复星火api上下文

* 将无星火ck的情况降低为warn

* feat: 添加星火设定自定义代码功能

* 修复星火api模式的一些问题

* 修复导出配置问题

* feat:添加工具箱快捷登录接口

* 添加工具箱快捷登录指令

* 阻止群聊使用快捷登录

* 添加Azure配置支持,修复重复的配置项冲突

* 移除旧版本渲染和新版本帮助

* 添加工具箱

* 更新工具箱替换原有后台

* 更新工具箱适配代码

* 后台适配Trss

* 修复trss不支持sendPrivateMsg的问题

* 优化路由

* 修复路由

* 适配其他uin

* 添加bing第三方绘图

* 修复bing绘图第三方调用错误

* 添加bing第三方绘图采样配置

* 修复错误

* 添加bing第三方绘图图片大小配置

* 修复视图错误

* 使用ap替换第三方绘图

* 适配trss

* server 适配trss

* 修复错误的后台版本更新

* 添加锅巴用户数据

* 修复server初始化消息错误

* 添加锅巴插件适配

* 更新后台页面

* 添加锅巴代理接口

* 优化锅巴接口代理

* 修复锅巴代理参数

* 删除调试信息

* 修复headers

* 更新后台锅巴插件支持

* 适配星火v3

* 适配星火v3

* 修复星火domain错误

* 修复更新后trss无法快捷登陆面板问题

* 奇怪的错误,忽略提示不影响使用
2023-12-08 11:53:19 +08:00
zyc404
b3c3990831 奇怪的错误,忽略提示不影响使用 2023-12-08 10:40:20 +08:00
zyc404
065d377bd0 修复更新后trss无法快捷登陆面板问题 2023-12-08 10:19:08 +08:00
zyc404
dd4476322f Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-12-08 10:04:17 +08:00
ikechan8370
46328a9716 fix: headers 2023-12-07 22:58:11 +08:00
ikechan8370
2183822bf0 fix: 权限 2023-12-07 22:46:35 +08:00
ikechan8370
91abd8a959 feat: refresh自动获取sessKey作为API Key 2023-12-07 22:41:44 +08:00
ikechan8370
f7ee904414 fix: api3 2023-12-07 20:36:26 +08:00
ikechan8370
8553525935 fix: 必应默认删除前戏 2023-12-04 15:26:32 +08:00
ikechan8370
407ef65967 fix: 移除悉尼,调整必应参数 2023-12-04 13:42:26 +08:00
zyc404
d795e8ea7d Merge branch 'v2' of https://github.com/HalcyonAlcedo/chatgpt-plugin; branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-12-04 13:41:00 +08:00
hanhan258
fac0863e3e
feat:指令查看模型列表,指令设置API模型、API反代、星火版本 (#616)
* fix: 修正fastify版本为4.18.0

* fix: 修正fastify版本为4.18.0

* fix:修复正则

* feat:指令查看模型列表,指令设置API模型、API反代、星火版本
2023-12-03 23:37:58 +08:00
ikechan8370
028fbb7528 fix: 嗯嗯 2023-11-28 19:08:47 +08:00
ikechan8370
823301e5c6 fix: 窒息 2023-11-28 15:19:22 +08:00
ikechan8370
b9ca5ce4e2 fix: shamrock的小问题 2023-11-28 14:40:40 +08:00
ikechan8370
88270f1bca fix: shamrock的小问题 2023-11-28 14:39:53 +08:00
ikechan8370
f1c2682ffe Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-11-28 14:30:21 +08:00
ikechan8370
cef2f7378d fix: shamrock的小问题 2023-11-28 14:30:09 +08:00
ikechan8370
aefea106a5 fix: #612 2023-11-28 00:31:59 +08:00
ikechan8370
1c6c10b118 fix: #613 2023-11-28 00:20:13 +08:00
ikechan8370
46d88c2669 fix: 修复喵崽多适配器工具箱登录;移除crypto依赖 2023-11-21 16:31:29 +08:00
ikechan8370
2b19302b87 fix: merge conflict 2023-11-21 15:43:48 +08:00
ikechan8370
f246e842ec fix: gl 2023-11-21 15:41:59 +08:00
ikechan8370
c99019cd91
fix: 跟进shamrock和lain的更新 2023-11-12 13:50:02 +08:00
zyc404
ef1423ddb4 Merge branch 'v2' of https://github.com/HalcyonAlcedo/chatgpt-plugin; branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-11-11 17:35:14 +08:00
ikechan8370
56a893734c fix: 降低词云阈值 2023-11-07 22:13:21 +08:00
ikechan8370
a45be2e211 fix: 词云bug 2023-11-07 22:11:09 +08:00
ikechan8370
0d8ef840d4 fix: 修复群名拿不到的问题 2023-11-07 21:59:34 +08:00
ikechan8370
e29e370f25 fix: 模型maxToken更新 gpt4后续更新 2023-11-07 21:37:38 +08:00
ikechan8370
ce65cc862f fix: 修复lain下部分工具失效问题 2023-11-07 19:59:10 +08:00
ikechan8370
e43b490edb fix: 修复microsoft-cognitiveservices-speech-sdk版本 2023-11-07 19:47:49 +08:00
ikechan8370
0bff8c85b0 feat: 进一步适配铃音+shamrock;词云进化 2023-11-07 18:54:58 +08:00
ikechan8370
61d3b48781 fix: 初步适配铃音语音 2023-11-04 11:49:36 +08:00
ikechan8370
7cc22e487a
Update README.md 2023-11-01 10:54:58 +08:00
ikechan8370
6c149265f0 fix: 修改必应初始对话次数为30 2023-10-30 17:00:53 +08:00
ikechan8370
7289ae6f35 fix: 优化首次使用插件bing模式下验证码请求被阻拦的问题 2023-10-30 17:00:26 +08:00
ikechan8370
ea687296a5 fix: 整理一些长期遗留懒得修的小问题 2023-10-30 15:35:05 +08:00
ikechan8370
e5959b0190
docs: Update README.md 2023-10-30 11:49:46 +08:00
ikechan8370
efa7fff574 fix: 复用API和千问模式的设定 2023-10-29 20:48:15 +08:00
ikechan8370
5cecea0783 fix: 千问结束全部对话bug 2023-10-29 20:19:31 +08:00
ikechan8370
2a713ca158 fix: reconstruction clients 2023-10-29 15:59:03 +08:00
HalcyonAlcedo
b7376407af
适配星火v3 (#598)
* fix: 修复星火api上下文

* 将无星火ck的情况降低为warn

* feat: 添加星火设定自定义代码功能

* 修复星火api模式的一些问题

* 修复导出配置问题

* feat:添加工具箱快捷登录接口

* 添加工具箱快捷登录指令

* 阻止群聊使用快捷登录

* 添加Azure配置支持,修复重复的配置项冲突

* 移除旧版本渲染和新版本帮助

* 添加工具箱

* 更新工具箱替换原有后台

* 更新工具箱适配代码

* 后台适配Trss

* 修复trss不支持sendPrivateMsg的问题

* 优化路由

* 修复路由

* 适配其他uin

* 添加bing第三方绘图

* 修复bing绘图第三方调用错误

* 添加bing第三方绘图采样配置

* 修复错误

* 添加bing第三方绘图图片大小配置

* 修复视图错误

* 使用ap替换第三方绘图

* 适配trss

* server 适配trss

* 修复错误的后台版本更新

* 添加锅巴用户数据

* 修复server初始化消息错误

* 添加锅巴插件适配

* 更新后台页面

* 添加锅巴代理接口

* 优化锅巴接口代理

* 修复锅巴代理参数

* 删除调试信息

* 修复headers

* 更新后台锅巴插件支持

* 适配星火v3

* 适配星火v3

* 修复星火domain错误
2023-10-25 23:06:10 +08:00
zyc404
cb6eb9c1eb 修复星火domain错误 2023-10-25 22:48:28 +08:00
zyc404
82af06a2da 适配星火v3 2023-10-25 22:39:35 +08:00
zyc404
32cc6a4e94 适配星火v3 2023-10-25 22:15:24 +08:00
zyc404
e0054521d3 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-10-25 22:13:42 +08:00
ikechan8370
c0936e6e2a feat: 增加通义千问支持 2023-10-25 21:50:44 +08:00
ikechan8370
d528840297 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-10-25 17:40:35 +08:00
ikechan8370
e0f96e3ac0 fix: 修复context覆盖的问题 2023-10-25 17:40:22 +08:00
ikechan8370
dc19009e2a fix: getUin错误 2023-10-21 16:06:31 +08:00
ikechan8370
9e7a614ded
fix: 修复不知道啥时候不小心碰到键盘导致的错误 2023-10-19 22:07:54 +08:00
ikechan8370
b1e3fb7892 fix: 减少必应接受的context长度不然爆炸 2023-10-19 21:12:53 +08:00
ikechan8370
74626e6676 fix: AI写的代码一定要检查 2023-10-19 21:02:14 +08:00
ikechan8370
3abfcc5d71 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-10-19 20:22:47 +08:00
ikechan8370
1a95c67130 feat: 为必应和claude2提供读取文件能力支持 2023-10-19 20:15:49 +08:00
ikechan8370
6d16861fe6
fix: update bing ai bundle version 2023-10-18 13:12:30 +08:00
HalcyonAlcedo
c68a50e8bc
继续适配Trss (#583)
* fix: 修复星火api上下文

* 将无星火ck的情况降低为warn

* feat: 添加星火设定自定义代码功能

* 修复星火api模式的一些问题

* 修复导出配置问题

* feat:添加工具箱快捷登录接口

* 添加工具箱快捷登录指令

* 阻止群聊使用快捷登录

* 添加Azure配置支持,修复重复的配置项冲突

* 移除旧版本渲染和新版本帮助

* 添加工具箱

* 更新工具箱替换原有后台

* 更新工具箱适配代码

* 后台适配Trss

* 修复trss不支持sendPrivateMsg的问题

* 优化路由

* 修复路由

* 适配其他uin

* 添加bing第三方绘图

* 修复bing绘图第三方调用错误

* 添加bing第三方绘图采样配置

* 修复错误

* 添加bing第三方绘图图片大小配置

* 修复视图错误

* 使用ap替换第三方绘图

* 适配trss

* server 适配trss

* 修复错误的后台版本更新

* 添加锅巴用户数据

* 修复server初始化消息错误

* 添加锅巴插件适配

* 更新后台页面

* 添加锅巴代理接口

* 优化锅巴接口代理

* 修复锅巴代理参数

* 删除调试信息

* 修复headers

* 更新后台锅巴插件支持
2023-10-16 21:49:00 +08:00
zyc404
48a2d64bf5 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-10-16 20:02:19 +08:00
zyc404
4cb4dc954e 更新后台锅巴插件支持 2023-10-16 19:55:43 +08:00
zyc404
03daaa66d7 修复headers 2023-10-16 18:50:52 +08:00
zyc404
ed568c40a4 删除调试信息 2023-10-16 18:46:35 +08:00
zyc404
14d7088e90 修复锅巴代理参数 2023-10-16 18:45:57 +08:00
zyc404
22ead6d55e 优化锅巴接口代理 2023-10-16 17:21:22 +08:00
ikechan8370
6c171b32a1 fix: 修复tts代理不正确问题 2023-10-16 16:57:52 +08:00
zyc404
fd735c1daf 添加锅巴代理接口 2023-10-16 14:40:27 +08:00
zyc404
f5a31f7601 更新后台页面 2023-10-15 19:19:19 +08:00
zyc404
7e5f723a82 添加锅巴插件适配 2023-10-15 19:17:24 +08:00
zyc404
42bad1cb47 修复server初始化消息错误 2023-10-15 17:36:34 +08:00
zyc404
471da4f3b1 添加锅巴用户数据 2023-10-15 17:33:57 +08:00
zyc404
ae14be4cf5 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-10-15 10:24:17 +08:00
ikechan8370
0e826e58a8 fix: 更新readme;隐藏日志 2023-10-15 01:31:12 +08:00
ikechan8370
1e867c08ef Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-10-15 00:08:14 +08:00
ikechan8370
83a82cf936 fix: 转发微调 2023-10-15 00:07:47 +08:00
zyc404
04bab7a894 修复错误的后台版本更新 2023-10-14 19:49:55 +08:00
zyc404
fb05cccd5b server 适配trss 2023-10-14 19:38:14 +08:00
zyc404
fe132985fd Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-10-14 17:13:48 +08:00
ikechan8370
4c16489ce1 fix: 回退 2023-10-14 13:25:59 +08:00
ikechan8370
a4ac59d8f9 fix: 兼容性修复 2023-10-14 13:14:59 +08:00
ikechan8370
e68c4fdd50 fix: 兼容性修复 2023-10-14 13:11:55 +08:00
ikechan8370
e4acfcf162 fix: 兼容性修复 2023-10-14 13:09:26 +08:00
ikechan8370
8b6fef00ec fix: 兼容性修复 2023-10-14 13:08:30 +08:00
ikechan8370
59ab8df658 fix: 兼容性修复 2023-10-14 13:07:01 +08:00
ikechan8370
4c737d5728 fix: 修复智能模式在TRSS下报错的问题 2023-10-14 12:55:41 +08:00
ikechan8370
0a3c95d305 fix: 某些特殊情况群聊记录 2023-10-14 01:11:53 +08:00
ikechan8370
4066f17847 fix: 修复TRSS转发错误,chronocat linux应该还没适配 2023-10-14 00:47:39 +08:00
ikechan8370
95e730f250 fix: 聊天记录适配TRSS+chronocat 2023-10-13 22:57:16 +08:00
ikechan8370
dce7503c41 fix: 微软更新后,第一次对话手动对话提示以避免无限循环 2023-10-13 22:15:06 +08:00
HalcyonAlcedo
ae58a20cc2
添加bing第三方绘图 (#580)
* fix: 修复星火api上下文

* 将无星火ck的情况降低为warn

* feat: 添加星火设定自定义代码功能

* 修复星火api模式的一些问题

* 修复导出配置问题

* feat:添加工具箱快捷登录接口

* 添加工具箱快捷登录指令

* 阻止群聊使用快捷登录

* 添加Azure配置支持,修复重复的配置项冲突

* 移除旧版本渲染和新版本帮助

* 添加工具箱

* 更新工具箱替换原有后台

* 更新工具箱适配代码

* 后台适配Trss

* 修复trss不支持sendPrivateMsg的问题

* 优化路由

* 修复路由

* 适配其他uin

* 添加bing第三方绘图

* 修复bing绘图第三方调用错误

* 添加bing第三方绘图采样配置

* 修复错误

* 添加bing第三方绘图图片大小配置

* 修复视图错误

* 使用ap替换第三方绘图

* 适配trss
2023-10-13 19:48:08 +08:00
zyc404
dfbee2011d 适配trss 2023-10-13 17:23:09 +08:00
zyc404
20ea8cfabf 使用ap替换第三方绘图 2023-10-13 12:17:45 +08:00
zyc404
0666de1aaa 修复视图错误 2023-10-12 17:20:47 +08:00
zyc404
096bcbca56 添加bing第三方绘图图片大小配置 2023-10-12 17:18:26 +08:00
zyc404
c5421bb5a0 修复错误 2023-10-12 17:03:07 +08:00
zyc404
a0a9630aba 添加bing第三方绘图采样配置 2023-10-12 16:59:50 +08:00
zyc404
7c45b050ca 修复bing绘图第三方调用错误 2023-10-12 16:50:06 +08:00
zyc404
fed2fd8dd4 添加bing第三方绘图 2023-10-12 16:31:20 +08:00
zyc404
8dcfb54e04 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-10-11 23:07:36 +08:00
ikechan8370
0f310a8ff3
fix: 对话反代默认开启 2023-10-08 21:52:04 +08:00
ikechan8370
e574681ad1
fix: 默认模式转为Sydney避免新装直接200 2023-10-08 21:50:30 +08:00
HalcyonAlcedo
0f9c8a7abe
适配Trss (#575)
* fix: 修复星火api上下文

* 将无星火ck的情况降低为warn

* feat: 添加星火设定自定义代码功能

* 修复星火api模式的一些问题

* 修复导出配置问题

* feat:添加工具箱快捷登录接口

* 添加工具箱快捷登录指令

* 阻止群聊使用快捷登录

* 添加Azure配置支持,修复重复的配置项冲突

* 移除旧版本渲染和新版本帮助

* 添加工具箱

* 更新工具箱替换原有后台

* 更新工具箱适配代码

* 后台适配Trss

* 修复trss不支持sendPrivateMsg的问题

* 优化路由

* 修复路由

* 适配其他uin
2023-10-08 21:37:43 +08:00
zyc404
e90d6f11ca 适配其他uin 2023-10-08 19:01:44 +08:00
zyc404
6e5ef2e1f5 修复路由 2023-10-08 18:56:08 +08:00
zyc404
d6fb62c424 优化路由 2023-10-08 18:48:34 +08:00
zyc404
5d5535ed6e 修复trss不支持sendPrivateMsg的问题 2023-10-08 18:34:41 +08:00
zyc404
880edace8a 后台适配Trss 2023-10-08 18:16:50 +08:00
zyc404
8aec804179 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-10-05 17:22:54 +08:00
ikechan8370
64f2699b22 fix: 适应必应API改版 2023-10-05 11:31:52 +08:00
ikechan8370
6e61d0e743 fix: update version 2023-09-23 20:26:48 +08:00
ikechan8370
390eb5cdae fix: update emojiData.json 2023-09-23 20:25:53 +08:00
ikechan8370
ad95327b1b fix: bingtoken国企 2023-09-23 20:13:26 +08:00
ikechan8370
7c5e9ea434 fix: 增加错误输出 2023-09-19 11:17:43 +08:00
ikechan8370
c36a0f9c9c fix: 延长claude超时时间 2023-09-19 11:03:23 +08:00
ikechan8370
77f6d2d85b fix: 增加claude.ai对话超时配置项 2023-09-19 09:47:48 +08:00
ikechan8370
08e92d871e fix: add support for claude.ai reverse proxy 2023-09-13 20:25:02 +08:00
ikechan8370
bb51e53e02 docs: update readme 2023-09-12 11:16:22 +08:00
ikechan8370
a91e2c25b3 fix: update forward 2023-09-12 11:14:08 +08:00
ikechan8370
f620e10abb fix: 兼容5和7的proxy依赖 2023-09-12 11:08:14 +08:00
ikechan8370
5e7d73908f feat: 支持自定义ja3 2023-09-11 14:27:22 +08:00
zyc404
c2c3052df1 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-09-10 13:00:25 +08:00
zyc404
c881090c08 Merge branch 'v2' of https://github.com/HalcyonAlcedo/chatgpt-plugin into v2 2023-09-10 12:59:46 +08:00
ikechan8370
078d31dc57 fix: import error 2023-09-08 22:07:56 +08:00
ikechan8370
b743259e78 feat: add ja3 support to enable claude2 2023-09-08 22:04:48 +08:00
ikechan8370
56d6b50aef
feat: Claude2 from claude.ai (#561)
* feat: claude2 test

* fix: node-fetch的bug,使用redirect暂时解决

* fix: field error

* fix: field error

* fix: 引用文件

* fix: filename error

* fix: ignore convert document error
2023-09-08 12:32:40 +08:00
HalcyonAlcedo
bf761c24da
修复bug和旧代码清理 (#553)
* fix: 修复星火api上下文

* 将无星火ck的情况降低为warn

* feat: 添加星火设定自定义代码功能

* 修复星火api模式的一些问题

* 修复导出配置问题

* feat:添加工具箱快捷登录接口

* 添加工具箱快捷登录指令

* 阻止群聊使用快捷登录

* 添加Azure配置支持,修复重复的配置项冲突

* 移除旧版本渲染和新版本帮助

* 添加工具箱

* 更新工具箱替换原有后台

* 更新工具箱适配代码
2023-09-08 12:28:02 +08:00
Alcedo
c3d998ec34 更新工具箱适配代码 2023-08-31 09:52:49 +08:00
Alcedo
6ace8720c4 更新工具箱替换原有后台 2023-08-31 09:45:16 +08:00
Alcedo
b966a09058 添加工具箱 2023-08-31 09:19:19 +08:00
Alcedo
6330eeb399 移除旧版本渲染和新版本帮助 2023-08-31 09:07:51 +08:00
Alcedo
57416dcd03 添加Azure配置支持,修复重复的配置项冲突 2023-08-31 08:51:39 +08:00
Alcedo
5028c2ea67 阻止群聊使用快捷登录 2023-08-30 17:06:22 +08:00
Alcedo
6a61722bc3 添加工具箱快捷登录指令 2023-08-30 16:55:22 +08:00
Alcedo
34f99a0160 feat:添加工具箱快捷登录接口 2023-08-30 10:11:34 +08:00
Alcedo
4457fab038 修复导出配置问题 2023-08-29 09:20:17 +08:00
Alcedo
b6c0a04285 修复星火api模式的一些问题 2023-08-29 08:49:07 +08:00
zyc404
43aa5ad105 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-08-27 14:22:20 +08:00
ikechan8370
043b80ddd4
fix: 移除一些headers以减少奇怪的502问题 2023-08-26 10:52:32 +08:00
Alcedo
791a438867 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-08-25 16:17:25 +08:00
Alcedo
007909a156 feat: 添加星火设定自定义代码功能 2023-08-25 15:29:25 +08:00
ikechan8370
d6ed1bf37f
fix: trim undefined error 2023-08-25 14:51:16 +08:00
Alcedo
d9c25140ac 将无星火ck的情况降低为warn 2023-08-25 14:21:31 +08:00
Alcedo
8df8626d1a fix: 修复星火api上下文 2023-08-25 14:05:44 +08:00
ikechan8370
246aaad987
fix: syntax error 2023-08-24 23:00:51 +08:00
sigeisment
502cc810bb
能否加入 Azure OpenAI 的相关支持 #471 (#536)
* 能否加入 Azure OpenAI 的相关支持 #471

* Azure OpenAI 锅巴配置

* 增加Azure OpenAI依赖

* 动态加载Azure OpenAI依赖

---------

Co-authored-by: sigeisment <zvdfka@gmail.com>
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-08-24 22:35:29 +08:00
HalcyonAlcedo
c2c6ea43de
添加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>
2023-08-24 22:33:23 +08:00
ikechan8370
3b1641ca5f
fix: add code verefication 2023-08-15 21:41:52 +08:00
HalcyonAlcedo
7ce058c4a5
后台和工具箱适配、添加群消息合并、优化bing绘图、修复引用空标题 (#530)
* 修复后台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: 修复绘图获取失败的问题

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-08-09 22:44:13 +08:00
TeaTing
4c26d7781a
feat. 兼容新版icqq转发消息 (#540)
* feat. 兼容新版icqq转发消息

feat. 兼容新版icqq转发消息

* 没改全。。。

没改全。。。

* fix: code format

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-08-09 22:41:42 +08:00
ikechan8370
4ffc6c1a32 fix: 调整对高版本HttpsProxyAgent支持的一个错误 2023-07-31 18:07:07 +08:00
ikechan8370
9c172e9e4b
Create stale.ymlchroe: add stale action 2023-07-30 20:46:49 +08:00
ikechan8370
407b3752a4 Merge branch 'v2' of https://github.com/ikechan8370/chatgpt-plugin into v2 2023-07-29 20:54:01 +08:00
ikechan8370
e4854e68f5 fix: 区分token过期和出验证码,避免大量无效过码请求和错误 2023-07-29 20:51:46 +08:00
ikechan8370
e445cb3c7f
必应验证码解决方案 (#528)
* feat: 必应验证码另一个解决方案

* fix: add log

* fix: try try

* fix: 优化报错信息
2023-07-28 23:58:29 +08:00
HalcyonAlcedo
709a1cebf0
优化和错误修复 (#527)
* 修复后台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: 修复错误的精度

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-07-28 20:14:26 +08:00
Sean Murphy
a703378cb1
限制了一些管理指令的触发条件防止误触 (#525)
* feat: add support for ‘greeting’ and ‘global reply mode’ commands, improve variable naming and remove unnecessary backend output.

* feat: Add support for black and white lists, global reply mode and voice role settings, private chat switch, and active greeting configuration. Refactor some variable names and comment out redundant code for better readability and reduced backend output.

* feat: 为新功能完善了帮助面板

* docs: 完善了‘打招呼’的帮助说明

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* refactor: Remove redundant log output.

* Refactor: optimize code logic

* Fix: 修复绘图指令表被抢指令的bug。

* Refactor:1. Add support for automatically translating replies to Japanese and generating voice messages in VITS voice mode (please monitor remaining quota after enabling). 2. Add translation function. 3. Add emotion configuration for Azure voice mode, allowing the robot to select appropriate emotional styles for replies.

* Refactor:Handle the issue of exceeding character setting limit caused by adding emotion configuration.

* Fix: fix bugs

* Refactor: Added error feedback to translation service

* Refactor: Added support for viewing the list of supported roles for each language mode, and fixed some bugs in the emotion switching feature of the auzre mode.

* Refactor: Optimized some command feedback and added owner restriction to chat record export function.

* Refactor: Optimized feedback when viewing role list to avoid excessive messages.

* Refactor: Optimized feedback when configuring multi-emotion mode.

* Feature: Added help instructions for translation feature.

* chore: Adjust help instructions for mood settings

* Fix: Fixed issue where only first line of multi-line replies were being read and Azure voice was pronouncing punctuation marks.

* Fix: Fixed bug where switching to Azure voice mode prompted for missing key and restricted ability to view voice role list to only when in voice mode.

* Refactor: Add image OCR function and support translation for both quoted text and image.

* fix: Fix issue with error caused by non-image input.

* Refactor: Optimize code to filter emojis that cannot be displayed properly in claude mode.

* Refactor: Optimize some code structures.

* fix: Fix the bug of returning only one result when entering multiple lines of text on Windows system.

* Refactor: Optimize code logic for better user experience

* Refactor: Fix the conflict issue with other plugin translation commands

* Refactor: Replace Baidu Translation with Youdao Translation to eliminate configuration steps; optimize translation experience; add missing dependency prompts instead of causing program errors.Optimize the experience of switching between voice mode and setting global reply mode.

* Refactor: Remove unused files and dependencies in the project.

* Feature: Add Youdao translation service to provide more comprehensive translation support.

* Refactor: Optimize translation experience

* Refactor: Optimize translation experience

* Feature: Add functionality of keyword search command

* Feature: Add functionality of keyword search command.

* Refactor: Remove redundant code

* Add: Add feature to support randomly selecting roles for Azure voice. Refactor the code to support existing voice services for the ‘greeting’ feature. Fix the display issue of Azure voice role selection on the Guoba panel.

* Refactor: Remove redundant code

* Refactor: Improve the function of setting global voice roles and viewing role lists. Now you can set default roles for each voice service separately or view the supported role list.

* Refactor: Remove redundant code

* Feature: Add new function to support random character dialogues in all voice modes, add the ability to view the current user’s reply settings, and improve related functions in the global settings.

* Refactor: Add compatibility directive for viewing reply settings feature

* Feature: support adding QQ number to blacklist/whitelist

* fix: 处理全局设置指令被上下班指令占用的问题

* fix: 处理全局设置指令被上下班指令占用的问题

* Refactor: Preprocess dialogue blacklist/whitelist when filling in the form in Guoba panel

* Fix: Fixed the issue where black and white lists were not effective when filled in the Guoba panel, and the issue where no results were returned when viewing the voice role list without parameters in azure tts mode.

* fix: 2.7 dev start

* feat: 初步支持function call(WIP)

* fix: syntax error

* fix: syntax error

* feat: 群聊上下文

* fix: 暂时阉割掉全员禁言功能

* fix: 修改禁言时间范围

* fix: 修复一些功能易用性

* fix: 只有管理员和群主才能用jinyan和kickout

* fix: 加回来禁言和踢出

* fix: 修复管理员权限判断问题(可能吧)

* fix: 试图优化逻辑

* fix: fuck openai documents

* fix: 删掉认主不然一直禁言我烦死了

* fix: 哔哩哔哩封面损坏问题

* fix: 加个天气小工具

* fix: 天气不存在城市

* fix: website工具用浏览器

* feat: serp tool

* feat: 增加一个google搜索源

* fix: 加一句描述

* feat: 增加搜索来源选项

* feat: 搜图和发图

* fix: groupId format error

* Refactor: Optimized the HTML parsing rules

* fix: Fixed the bug where conversations could not be properly ended in at mode, now it works normally

* refactor: Added EliMovieTool and EliMusicTool. Modified some tool’s prompt to make AI make better choices. Optimized the display of chat history.Remove SendMusicTool and replace it with EliMusicTool.

* chore: trivial changes.

* refactor:Keep SearchMusicTool and SendMusicTool when avocado plugin is not installed, waiting for more testing~~~

* Refactor: Move the parameter processing logic of some tools into each tool internally.🥑Rename ttstool to SendAudioMessageTool, defaulting to the voice role configured by the current user, and support personalized configuration of the existing tts mode in the plugin.🥑Add SendMessageToSpecificGroupOrUserTool, which allows the robot to send messages to specific groups or friends.🥑Encapsulate the function of generating audio messages into an independent function for easy tool invocation.🥑Separate SendPictureTool and SendAvatarTool to avoid unnecessary bugs.🥑

* chore: Remove unnecessary log file🥑

* refactor: Trivial changes and fixed a bug in QueryUserinfoTool.🥑

* Refactor: Rewrite blacklist and whitelist functionality, optimize code calls Description: Rewrote the blacklist and whitelist functionality to support group, QQ number, and a combination of group and QQ number configurations. Removed the command to set the blacklist and whitelist functionality and unified it through the Guoba panel. Also optimized some code calls to EliMusicTool and EliMovieTool.🥑

* chore: Adjust some tool prompts

* chore: adjust prompt

* Refactor: Improve the user experience of EliMovieTool and EliMusicTool🥑

* Fix: Fix the bug that AI sends content to itself using the tool🥑

* refactor: Instructions adapted to the new version of avocado-plugin

* refactor: optimize avocadoRender🥑

* Chore: Optimize regex commands related to management functions

* Chore: trivial changes

---------

Co-authored-by: Sean <1519059137@qq.com>
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
Co-authored-by: ikechan8370 <geyinchi@buaa.edu.cn>
2023-07-28 20:13:56 +08:00
ikechan8370
12a94d8086 feat: 必应验证码另一个解决方案 2023-07-28 14:20:55 +08:00
ikechan8370
51f786bd44 fix: 修改默认搜索引擎为必应 2023-07-23 21:24:26 +08:00
ikechan8370
b1570d6126 fix: 回退部分修改;增加验证码提示词 2023-07-23 21:21:32 +08:00
ikechan8370
ef57259e8a fix: bing captcha fix(不建议升级) 2023-07-22 02:58:45 +08:00
ikechan8370
521914bb5b fix: 修改context 2023-07-22 02:04:07 +08:00
ikechan8370
5d6737d24a feat: 必应验证码(beta) 2023-07-22 00:01:05 +08:00
ikechan8370
bc072d965d fix: 修改依赖版本 2023-07-20 12:35:32 +08:00
HalcyonAlcedo
492a805647
修复图片识别bug (#518)
* 修复后台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无法调用,尝试添加反代

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

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-07-20 11:30:28 +08:00
HalcyonAlcedo
6ee0b0ead9
添加Sydney图片识别,适配tools接口 (#516)
* 修复后台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配置

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-07-19 16:30:17 +08:00
ikechan8370
ffb0929ab9
Update README.md 2023-07-17 14:07:36 +08:00
ikechan8370
6628b8837b fix: add trim 2023-07-15 21:17:45 +08:00
ikechan8370
a1b450abaa fix: 智能模式function叠加消息 2023-07-15 14:24:05 +08:00
ikechan8370
b5669de782 fix: remove unuseful fields to reduce token usage 2023-07-10 11:18:15 +08:00
ikechan8370
db24de9ae3 fix: stream模式下function_all参数问题 2023-07-09 22:12:45 +08:00
ikechan8370
b35a2a9999 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-07-09 21:58:55 +08:00
ikechan8370
b9f45c2052 feat: support stream debug log 2023-07-09 21:58:49 +08:00
Sean Murphy
75672586ca
修复机器人使用工具发送内容会发送给自己的bug, tool适配新版鳄梨插件的指令. (#506)
* feat: add support for ‘greeting’ and ‘global reply mode’ commands, improve variable naming and remove unnecessary backend output.

* feat: Add support for black and white lists, global reply mode and voice role settings, private chat switch, and active greeting configuration. Refactor some variable names and comment out redundant code for better readability and reduced backend output.

* feat: 为新功能完善了帮助面板

* docs: 完善了‘打招呼’的帮助说明

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* refactor: Remove redundant log output.

* Refactor: optimize code logic

* Fix: 修复绘图指令表被抢指令的bug。

* Refactor:1. Add support for automatically translating replies to Japanese and generating voice messages in VITS voice mode (please monitor remaining quota after enabling). 2. Add translation function. 3. Add emotion configuration for Azure voice mode, allowing the robot to select appropriate emotional styles for replies.

* Refactor:Handle the issue of exceeding character setting limit caused by adding emotion configuration.

* Fix: fix bugs

* Refactor: Added error feedback to translation service

* Refactor: Added support for viewing the list of supported roles for each language mode, and fixed some bugs in the emotion switching feature of the auzre mode.

* Refactor: Optimized some command feedback and added owner restriction to chat record export function.

* Refactor: Optimized feedback when viewing role list to avoid excessive messages.

* Refactor: Optimized feedback when configuring multi-emotion mode.

* Feature: Added help instructions for translation feature.

* chore: Adjust help instructions for mood settings

* Fix: Fixed issue where only first line of multi-line replies were being read and Azure voice was pronouncing punctuation marks.

* Fix: Fixed bug where switching to Azure voice mode prompted for missing key and restricted ability to view voice role list to only when in voice mode.

* Refactor: Add image OCR function and support translation for both quoted text and image.

* fix: Fix issue with error caused by non-image input.

* Refactor: Optimize code to filter emojis that cannot be displayed properly in claude mode.

* Refactor: Optimize some code structures.

* fix: Fix the bug of returning only one result when entering multiple lines of text on Windows system.

* Refactor: Optimize code logic for better user experience

* Refactor: Fix the conflict issue with other plugin translation commands

* Refactor: Replace Baidu Translation with Youdao Translation to eliminate configuration steps; optimize translation experience; add missing dependency prompts instead of causing program errors.Optimize the experience of switching between voice mode and setting global reply mode.

* Refactor: Remove unused files and dependencies in the project.

* Feature: Add Youdao translation service to provide more comprehensive translation support.

* Refactor: Optimize translation experience

* Refactor: Optimize translation experience

* Feature: Add functionality of keyword search command

* Feature: Add functionality of keyword search command.

* Refactor: Remove redundant code

* Add: Add feature to support randomly selecting roles for Azure voice. Refactor the code to support existing voice services for the ‘greeting’ feature. Fix the display issue of Azure voice role selection on the Guoba panel.

* Refactor: Remove redundant code

* Refactor: Improve the function of setting global voice roles and viewing role lists. Now you can set default roles for each voice service separately or view the supported role list.

* Refactor: Remove redundant code

* Feature: Add new function to support random character dialogues in all voice modes, add the ability to view the current user’s reply settings, and improve related functions in the global settings.

* Refactor: Add compatibility directive for viewing reply settings feature

* Feature: support adding QQ number to blacklist/whitelist

* fix: 处理全局设置指令被上下班指令占用的问题

* fix: 处理全局设置指令被上下班指令占用的问题

* Refactor: Preprocess dialogue blacklist/whitelist when filling in the form in Guoba panel

* Fix: Fixed the issue where black and white lists were not effective when filled in the Guoba panel, and the issue where no results were returned when viewing the voice role list without parameters in azure tts mode.

* fix: 2.7 dev start

* feat: 初步支持function call(WIP)

* fix: syntax error

* fix: syntax error

* feat: 群聊上下文

* fix: 暂时阉割掉全员禁言功能

* fix: 修改禁言时间范围

* fix: 修复一些功能易用性

* fix: 只有管理员和群主才能用jinyan和kickout

* fix: 加回来禁言和踢出

* fix: 修复管理员权限判断问题(可能吧)

* fix: 试图优化逻辑

* fix: fuck openai documents

* fix: 删掉认主不然一直禁言我烦死了

* fix: 哔哩哔哩封面损坏问题

* fix: 加个天气小工具

* fix: 天气不存在城市

* fix: website工具用浏览器

* feat: serp tool

* feat: 增加一个google搜索源

* fix: 加一句描述

* feat: 增加搜索来源选项

* feat: 搜图和发图

* fix: groupId format error

* Refactor: Optimized the HTML parsing rules

* fix: Fixed the bug where conversations could not be properly ended in at mode, now it works normally

* refactor: Added EliMovieTool and EliMusicTool. Modified some tool’s prompt to make AI make better choices. Optimized the display of chat history.Remove SendMusicTool and replace it with EliMusicTool.

* chore: trivial changes.

* refactor:Keep SearchMusicTool and SendMusicTool when avocado plugin is not installed, waiting for more testing~~~

* Refactor: Move the parameter processing logic of some tools into each tool internally.🥑Rename ttstool to SendAudioMessageTool, defaulting to the voice role configured by the current user, and support personalized configuration of the existing tts mode in the plugin.🥑Add SendMessageToSpecificGroupOrUserTool, which allows the robot to send messages to specific groups or friends.🥑Encapsulate the function of generating audio messages into an independent function for easy tool invocation.🥑Separate SendPictureTool and SendAvatarTool to avoid unnecessary bugs.🥑

* chore: Remove unnecessary log file🥑

* refactor: Trivial changes and fixed a bug in QueryUserinfoTool.🥑

* Refactor: Rewrite blacklist and whitelist functionality, optimize code calls Description: Rewrote the blacklist and whitelist functionality to support group, QQ number, and a combination of group and QQ number configurations. Removed the command to set the blacklist and whitelist functionality and unified it through the Guoba panel. Also optimized some code calls to EliMusicTool and EliMovieTool.🥑

* chore: Adjust some tool prompts

* chore: adjust prompt

* Refactor: Improve the user experience of EliMovieTool and EliMusicTool🥑

* Fix: Fix the bug that AI sends content to itself using the tool🥑

* refactor: Instructions adapted to the new version of avocado-plugin

---------

Co-authored-by: Sean <1519059137@qq.com>
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
Co-authored-by: ikechan8370 <geyinchi@buaa.edu.cn>
2023-07-08 16:50:51 +08:00
ikechan8370
66172feb3e fix: 默认使用百度搜索引擎 2023-07-05 15:16:02 +08:00
ikechan8370
4ad4119c39 fix: 无法发送音乐的问题 2023-07-05 14:13:00 +08:00
ikechan8370
e1406a8c58
Update README.md 2023-07-05 00:55:59 +08:00
ikechan8370
7ca35836bf fix: whiletlist的未知问题;修改文档 2023-07-04 21:27:01 +08:00
ikechan8370
636963af0e feat: OpenAI余额查询功能 2023-07-04 16:30:31 +08:00
ikechan8370
3b807211c2 fix: group 2023-07-03 11:21:47 +08:00
ikechan8370
9be8b54faf feat: give title 2023-07-03 01:19:11 +08:00
ikechan8370
8a531bf551 fix: 微调必应 2023-07-03 01:05:34 +08:00
ikechan8370
e42307fd76 fix: qq.trim 2023-07-03 00:51:17 +08:00
ikechan8370
89416677fb
Update README.md 2023-07-03 00:39:59 +08:00
ikechan8370
f1da0d36d9 fix: 更换website总结网站内容默认模型 2023-07-01 21:56:20 +08:00
ikechan8370
80b320ff3a fix: 修复openai client由于计算token引起的错误 2023-07-01 21:50:26 +08:00
ikechan8370
285afad993 fix: 修复website tool的bug(啊) 2023-07-01 21:42:12 +08:00
ikechan8370
6ba96eecc7 fix: 修复非智能模式的functions报错 2023-07-01 21:29:48 +08:00
ikechan8370
dd249615e4 fix: try to add required token 2023-07-01 16:44:52 +08:00
ikechan8370
53ad413f52 fix: revert fetch-sse 2023-07-01 16:38:43 +08:00
ikechan8370
f01d1d3998 fix: 修复token计算方法 2023-07-01 16:36:51 +08:00
ikechan8370
a94017e6e5 fix: add more debug log 2023-07-01 16:31:17 +08:00
ikechan8370
877b91c765 fix: print error 2023-07-01 16:02:45 +08:00
ikechan8370
ff69d2e963 fix: syntax error 2023-07-01 15:57:27 +08:00
ikechan8370
e5d43a8cc1 fix: version 2.7.2 2023-07-01 15:55:27 +08:00
ikechan8370
7a8b30db14 fix: merge tons of conflict 2023-07-01 15:55:07 +08:00
ikechan8370
f0b717bed8 fix: 修复 2023-07-01 15:49:21 +08:00
ikechan8370
9838459446 fix: 修复一些智能模式的问题 2023-07-01 15:48:01 +08:00
HalcyonAlcedo
ca3788d719
feat: 新增对tool支持的相关接口 (#495)
* 修复后台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相关代码

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-07-01 15:47:07 +08:00
Sean Murphy
2443ed6f71
🥵🥵🥵 (#496)
* feat: add support for ‘greeting’ and ‘global reply mode’ commands, improve variable naming and remove unnecessary backend output.

* feat: Add support for black and white lists, global reply mode and voice role settings, private chat switch, and active greeting configuration. Refactor some variable names and comment out redundant code for better readability and reduced backend output.

* feat: 为新功能完善了帮助面板

* docs: 完善了‘打招呼’的帮助说明

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* refactor: Remove redundant log output.

* Refactor: optimize code logic

* Fix: 修复绘图指令表被抢指令的bug。

* Refactor:1. Add support for automatically translating replies to Japanese and generating voice messages in VITS voice mode (please monitor remaining quota after enabling). 2. Add translation function. 3. Add emotion configuration for Azure voice mode, allowing the robot to select appropriate emotional styles for replies.

* Refactor:Handle the issue of exceeding character setting limit caused by adding emotion configuration.

* Fix: fix bugs

* Refactor: Added error feedback to translation service

* Refactor: Added support for viewing the list of supported roles for each language mode, and fixed some bugs in the emotion switching feature of the auzre mode.

* Refactor: Optimized some command feedback and added owner restriction to chat record export function.

* Refactor: Optimized feedback when viewing role list to avoid excessive messages.

* Refactor: Optimized feedback when configuring multi-emotion mode.

* Feature: Added help instructions for translation feature.

* chore: Adjust help instructions for mood settings

* Fix: Fixed issue where only first line of multi-line replies were being read and Azure voice was pronouncing punctuation marks.

* Fix: Fixed bug where switching to Azure voice mode prompted for missing key and restricted ability to view voice role list to only when in voice mode.

* Refactor: Add image OCR function and support translation for both quoted text and image.

* fix: Fix issue with error caused by non-image input.

* Refactor: Optimize code to filter emojis that cannot be displayed properly in claude mode.

* Refactor: Optimize some code structures.

* fix: Fix the bug of returning only one result when entering multiple lines of text on Windows system.

* Refactor: Optimize code logic for better user experience

* Refactor: Fix the conflict issue with other plugin translation commands

* Refactor: Replace Baidu Translation with Youdao Translation to eliminate configuration steps; optimize translation experience; add missing dependency prompts instead of causing program errors.Optimize the experience of switching between voice mode and setting global reply mode.

* Refactor: Remove unused files and dependencies in the project.

* Feature: Add Youdao translation service to provide more comprehensive translation support.

* Refactor: Optimize translation experience

* Refactor: Optimize translation experience

* Feature: Add functionality of keyword search command

* Feature: Add functionality of keyword search command.

* Refactor: Remove redundant code

* Add: Add feature to support randomly selecting roles for Azure voice. Refactor the code to support existing voice services for the ‘greeting’ feature. Fix the display issue of Azure voice role selection on the Guoba panel.

* Refactor: Remove redundant code

* Refactor: Improve the function of setting global voice roles and viewing role lists. Now you can set default roles for each voice service separately or view the supported role list.

* Refactor: Remove redundant code

* Feature: Add new function to support random character dialogues in all voice modes, add the ability to view the current user’s reply settings, and improve related functions in the global settings.

* Refactor: Add compatibility directive for viewing reply settings feature

* Feature: support adding QQ number to blacklist/whitelist

* fix: 处理全局设置指令被上下班指令占用的问题

* fix: 处理全局设置指令被上下班指令占用的问题

* Refactor: Preprocess dialogue blacklist/whitelist when filling in the form in Guoba panel

* Fix: Fixed the issue where black and white lists were not effective when filled in the Guoba panel, and the issue where no results were returned when viewing the voice role list without parameters in azure tts mode.

* fix: 2.7 dev start

* feat: 初步支持function call(WIP)

* fix: syntax error

* fix: syntax error

* feat: 群聊上下文

* fix: 暂时阉割掉全员禁言功能

* fix: 修改禁言时间范围

* fix: 修复一些功能易用性

* fix: 只有管理员和群主才能用jinyan和kickout

* fix: 加回来禁言和踢出

* fix: 修复管理员权限判断问题(可能吧)

* fix: 试图优化逻辑

* fix: fuck openai documents

* fix: 删掉认主不然一直禁言我烦死了

* fix: 哔哩哔哩封面损坏问题

* fix: 加个天气小工具

* fix: 天气不存在城市

* fix: website工具用浏览器

* feat: serp tool

* feat: 增加一个google搜索源

* fix: 加一句描述

* feat: 增加搜索来源选项

* feat: 搜图和发图

* fix: groupId format error

* Refactor: Optimized the HTML parsing rules

* fix: Fixed the bug where conversations could not be properly ended in at mode, now it works normally

* refactor: Added EliMovieTool and EliMusicTool. Modified some tool’s prompt to make AI make better choices. Optimized the display of chat history.Remove SendMusicTool and replace it with EliMusicTool.

* chore: trivial changes.

* refactor:Keep SearchMusicTool and SendMusicTool when avocado plugin is not installed, waiting for more testing~~~

* Refactor: Move the parameter processing logic of some tools into each tool internally.🥑Rename ttstool to SendAudioMessageTool, defaulting to the voice role configured by the current user, and support personalized configuration of the existing tts mode in the plugin.🥑Add SendMessageToSpecificGroupOrUserTool, which allows the robot to send messages to specific groups or friends.🥑Encapsulate the function of generating audio messages into an independent function for easy tool invocation.🥑Separate SendPictureTool and SendAvatarTool to avoid unnecessary bugs.🥑

* chore: Remove unnecessary log file🥑

* refactor: Trivial changes and fixed a bug in QueryUserinfoTool.🥑

* Refactor: Rewrite blacklist and whitelist functionality, optimize code calls Description: Rewrote the blacklist and whitelist functionality to support group, QQ number, and a combination of group and QQ number configurations. Removed the command to set the blacklist and whitelist functionality and unified it through the Guoba panel. Also optimized some code calls to EliMusicTool and EliMovieTool.🥑

---------

Co-authored-by: Sean <1519059137@qq.com>
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
Co-authored-by: ikechan8370 <geyinchi@buaa.edu.cn>
2023-07-01 15:46:15 +08:00
ikechan8370
36e592e773 fix: 稍微修改一下bing ws 2023-06-29 11:54:05 +08:00
ikechan8370
d4a3b2ce61
fix: update fastify 2023-06-28 09:44:32 +08:00
ikechan8370
962bde1beb
Update README.md (#493) 2023-06-26 20:05:05 +08:00
ikechan8370
8acb3f48e7 fix: image caption qq error 2023-06-26 15:48:17 +08:00
ikechan8370
c6ce17ff98 fix: 生气了 2023-06-26 15:39:12 +08:00
ikechan8370
1a73940231 fix: 调整一些prompt 2023-06-26 15:23:33 +08:00
ikechan8370
aed271479d fix: 撤回tool的问题 2023-06-26 14:59:18 +08:00
ikechan8370
ca28b00679 feat: 一些小工具 2023-06-26 14:50:43 +08:00
ikechan8370
c99af43571 fix: genshin tool fix 2023-06-26 13:47:35 +08:00
ikechan8370
8bc5829777 fix: 修复miaoplugin 2023-06-26 13:34:57 +08:00
ikechan8370
328849b320 fix: 优化一些tool 2023-06-26 13:25:00 +08:00
ikechan8370
8257779f5c fix: 优化一些tool 2023-06-26 13:17:14 +08:00
Maitaozi
b7ac3bff30
解决非QQ平台AI回复后依然发送异常图片 (#491) 2023-06-26 02:56:04 +08:00
ikechan8370
16a8c64b56 fix: 漏了一个tool 2023-06-25 23:20:30 +08:00
ikechan8370
d3cc6e4679 fix: delete a 2023-06-25 23:19:54 +08:00
ikechan8370
ced2b4eeb6 feat: add a tool 2023-06-25 23:18:54 +08:00
ikechan8370
87182f1a1f fix: 修复sr 2023-06-25 20:25:37 +08:00
ikechan8370
9f7a51679f fix: 这户i对了吧 2023-06-25 19:45:40 +08:00
ikechan8370
3427d23054 fix: try 2023-06-25 18:52:08 +08:00
ikechan8370
bcb19db162 fix: ? 2023-06-25 18:47:34 +08:00
ikechan8370
46dc1a8c39 fix: sr 2023-06-25 18:45:31 +08:00
ikechan8370
fc029de75c fix: update sr 2023-06-25 18:42:34 +08:00
ikechan8370
7e559881eb fix: 原来是这样 2023-06-25 18:36:27 +08:00
ikechan8370
37572bd635 fix: 修复ap默认at机器人的问题 2023-06-25 18:32:59 +08:00
ikechan8370
6e912d68c8 fix: 支持ap的dev分支 2023-06-25 18:24:00 +08:00
ikechan8370
a35f8a31a0 feat: try to support ap-plugin 2023-06-25 18:07:23 +08:00
ikechan8370
03b02442fa fix: bump version 2023-06-25 17:33:28 +08:00
ikechan8370
feb6b31994 fix: groupId 格式问题 2023-06-25 17:31:09 +08:00
ikechan8370
de8cc48156 fix: tts role 2023-06-25 16:48:29 +08:00
ikechan8370
d52f95780a fix: tts tool 2023-06-25 16:46:48 +08:00
ikechan8370
38383e373e fix: 啊啊啊 2023-06-25 16:22:27 +08:00
ikechan8370
cd1687299a fix: 啊 2023-06-25 16:21:32 +08:00
ikechan8370
8c7e6489e7 fix: 啊 2023-06-25 16:17:23 +08:00
ikechan8370
19f9c804bb feat: add a tool 2023-06-25 16:10:23 +08:00
ikechan8370
116e4bef3c feat: add a tool 2023-06-25 16:09:58 +08:00
ikechan8370
da27e6a1b3 feat: add a tts tool 2023-06-25 16:09:47 +08:00
ikechan8370
c3d9f65a03 fix: 删掉多余的提示 2023-06-25 15:08:47 +08:00
ikechan8370
8a32f7e4fd fix: add visual qa 2023-06-25 15:01:56 +08:00
ikechan8370
faed389835 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-06-25 14:40:33 +08:00
HalcyonAlcedo
7bc140a030
fix: 修复后台面板无法访问的问题 (#490) 2023-06-25 12:24:31 +08:00
ikechan8370
5bfd55e765 fix: 删掉惩罚 2023-06-25 01:52:25 +08:00
ikechan8370
14369c8f90 fix: 又漏了一个tool 2023-06-25 01:38:46 +08:00
ikechan8370
2c2e71fb4d fix: 漏了一个tool 2023-06-25 01:37:23 +08:00
ikechan8370
33f80519a6 fix: 满足AI的任性需求 2023-06-25 01:24:13 +08:00
ikechan8370
637c921130 fix: 修正fastify版本 2023-06-25 01:20:06 +08:00
ikechan8370
8c463c731f fix: add dependencies 2023-06-25 01:14:53 +08:00
ikechan8370
0dedaf7516 fix: 修正依赖 2023-06-25 01:12:36 +08:00
ikechan8370
b7427e74c4
feat: 智能模式,添加群管、试图、联网搜索、发图、发音乐和视频等功能 (#488)
* fix: 2.7 dev start

* feat: 初步支持function call(WIP)

* fix: syntax error

* fix: syntax error

* feat: 群聊上下文

* fix: 暂时阉割掉全员禁言功能

* fix: 修改禁言时间范围

* fix: 修复一些功能易用性

* fix: 只有管理员和群主才能用jinyan和kickout

* fix: 加回来禁言和踢出

* fix: 修复管理员权限判断问题(可能吧)

* fix: 试图优化逻辑

* fix: fuck openai documents

* fix: 删掉认主不然一直禁言我烦死了

* fix: 哔哩哔哩封面损坏问题

* fix: 加个天气小工具

* fix: 天气不存在城市

* fix: website工具用浏览器

* feat: serp tool

* feat: 增加一个google搜索源

* fix: 加一句描述

* feat: 增加搜索来源选项

* feat: 搜图和发图

* fix: groupId format error

* fix: add a image caption tool

* fix: 修改一些提示。tool太多机器人开始混乱了

* fix: 一些极端的措施

* fix: 增加一些提示和一个暂时的公共接口

* fix: 收拾一下

* fix: 修改命令正则

* fix: 修改一些提示

* fix: move send avatar into send picture tool

* fix: 修复解除禁言的bug
2023-06-25 01:09:29 +08:00
Sean Murphy
2c5b084b04
修复在guoba面板填写黑白名单不生效的bug,修复azure语音模式下无参数查看语音角色列表时不返回结果的bug。 (#476)
* feat: add support for ‘greeting’ and ‘global reply mode’ commands, improve variable naming and remove unnecessary backend output.

* feat: Add support for black and white lists, global reply mode and voice role settings, private chat switch, and active greeting configuration. Refactor some variable names and comment out redundant code for better readability and reduced backend output.

* feat: 为新功能完善了帮助面板

* docs: 完善了‘打招呼’的帮助说明

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* refactor: Remove redundant log output.

* Refactor: optimize code logic

* Fix: 修复绘图指令表被抢指令的bug。

* Refactor:1. Add support for automatically translating replies to Japanese and generating voice messages in VITS voice mode (please monitor remaining quota after enabling). 2. Add translation function. 3. Add emotion configuration for Azure voice mode, allowing the robot to select appropriate emotional styles for replies.

* Refactor:Handle the issue of exceeding character setting limit caused by adding emotion configuration.

* Fix: fix bugs

* Refactor: Added error feedback to translation service

* Refactor: Added support for viewing the list of supported roles for each language mode, and fixed some bugs in the emotion switching feature of the auzre mode.

* Refactor: Optimized some command feedback and added owner restriction to chat record export function.

* Refactor: Optimized feedback when viewing role list to avoid excessive messages.

* Refactor: Optimized feedback when configuring multi-emotion mode.

* Feature: Added help instructions for translation feature.

* chore: Adjust help instructions for mood settings

* Fix: Fixed issue where only first line of multi-line replies were being read and Azure voice was pronouncing punctuation marks.

* Fix: Fixed bug where switching to Azure voice mode prompted for missing key and restricted ability to view voice role list to only when in voice mode.

* Refactor: Add image OCR function and support translation for both quoted text and image.

* fix: Fix issue with error caused by non-image input.

* Refactor: Optimize code to filter emojis that cannot be displayed properly in claude mode.

* Refactor: Optimize some code structures.

* fix: Fix the bug of returning only one result when entering multiple lines of text on Windows system.

* Refactor: Optimize code logic for better user experience

* Refactor: Fix the conflict issue with other plugin translation commands

* Refactor: Replace Baidu Translation with Youdao Translation to eliminate configuration steps; optimize translation experience; add missing dependency prompts instead of causing program errors.Optimize the experience of switching between voice mode and setting global reply mode.

* Refactor: Remove unused files and dependencies in the project.

* Feature: Add Youdao translation service to provide more comprehensive translation support.

* Refactor: Optimize translation experience

* Refactor: Optimize translation experience

* Feature: Add functionality of keyword search command

* Feature: Add functionality of keyword search command.

* Refactor: Remove redundant code

* Add: Add feature to support randomly selecting roles for Azure voice. Refactor the code to support existing voice services for the ‘greeting’ feature. Fix the display issue of Azure voice role selection on the Guoba panel.

* Refactor: Remove redundant code

* Refactor: Improve the function of setting global voice roles and viewing role lists. Now you can set default roles for each voice service separately or view the supported role list.

* Refactor: Remove redundant code

* Feature: Add new function to support random character dialogues in all voice modes, add the ability to view the current user’s reply settings, and improve related functions in the global settings.

* Refactor: Add compatibility directive for viewing reply settings feature

* Feature: support adding QQ number to blacklist/whitelist

* fix: 处理全局设置指令被上下班指令占用的问题

* fix: 处理全局设置指令被上下班指令占用的问题

* Refactor: Preprocess dialogue blacklist/whitelist when filling in the form in Guoba panel

* Fix: Fixed the issue where black and white lists were not effective when filled in the Guoba panel, and the issue where no results were returned when viewing the voice role list without parameters in azure tts mode.

---------

Co-authored-by: Sean <1519059137@qq.com>
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-06-25 00:59:02 +08:00
HalcyonAlcedo
a3fab7316f
feat: 新增ws接口,适配工具 (#482)
* 修复后台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参数

* 添加群消息获取权限

* 添加用户多端登录支持

* 修复错误的路径引用

* 修复错误的路径引用

* 修复错误

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

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-06-25 00:58:41 +08:00
ikechan8370
85e9d079a5 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-06-17 15:31:27 +08:00
ikechan8370
d7cb9aa56d fix: unknown 2023-06-17 15:31:19 +08:00
TeaTing
fbe8953667
🥰更改chatgpt-plugin的更新代码顺便修复一个正则问题 (#450)
* 改进ChatGPT-Plugin的更新代码

* 删除旧更新

* 增加声明

* 更改文件编码

* 更改正则触发表达式

* 修复一个正则问题,防止抢了ap的#指令表
2023-06-17 12:07:14 +08:00
ikechan8370
adc0817731
fix: 把随机系统消息加回来 2023-06-16 19:48:09 +08:00
HalcyonAlcedo
317283218a
feat: 适配远程渲染服务器,优化Live2D (#463)
* 修复后台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配置

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-06-12 21:38:38 +08:00
ikechan8370
508beaece3
fix: 可能能解决findIndex 2023-06-10 16:23:16 +08:00
Sean Murphy
bdad936c70
feat: 黑白名单支持配置qq号;支持所有语音模式下的随机角色对话;新增查看当前用户的回复设置;完善全局设置的相关功能;支持为Azure语音服务随机选择角色;优化设置全局语音角色和查看角色列表的功能;重构了代码以支持现有语音服务的打招呼功能;修复了Guoba面板上Azure语音角色选择的显示问题。 (#436)
* feat: add support for ‘greeting’ and ‘global reply mode’ commands, improve variable naming and remove unnecessary backend output.

* feat: Add support for black and white lists, global reply mode and voice role settings, private chat switch, and active greeting configuration. Refactor some variable names and comment out redundant code for better readability and reduced backend output.

* feat: 为新功能完善了帮助面板

* docs: 完善了‘打招呼’的帮助说明

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* refactor: Remove redundant log output.

* Refactor: optimize code logic

* Fix: 修复绘图指令表被抢指令的bug。

* Refactor:1. Add support for automatically translating replies to Japanese and generating voice messages in VITS voice mode (please monitor remaining quota after enabling). 2. Add translation function. 3. Add emotion configuration for Azure voice mode, allowing the robot to select appropriate emotional styles for replies.

* Refactor:Handle the issue of exceeding character setting limit caused by adding emotion configuration.

* Fix: fix bugs

* Refactor: Added error feedback to translation service

* Refactor: Added support for viewing the list of supported roles for each language mode, and fixed some bugs in the emotion switching feature of the auzre mode.

* Refactor: Optimized some command feedback and added owner restriction to chat record export function.

* Refactor: Optimized feedback when viewing role list to avoid excessive messages.

* Refactor: Optimized feedback when configuring multi-emotion mode.

* Feature: Added help instructions for translation feature.

* chore: Adjust help instructions for mood settings

* Fix: Fixed issue where only first line of multi-line replies were being read and Azure voice was pronouncing punctuation marks.

* Fix: Fixed bug where switching to Azure voice mode prompted for missing key and restricted ability to view voice role list to only when in voice mode.

* Refactor: Add image OCR function and support translation for both quoted text and image.

* fix: Fix issue with error caused by non-image input.

* Refactor: Optimize code to filter emojis that cannot be displayed properly in claude mode.

* Refactor: Optimize some code structures.

* fix: Fix the bug of returning only one result when entering multiple lines of text on Windows system.

* Refactor: Optimize code logic for better user experience

* Refactor: Fix the conflict issue with other plugin translation commands

* Refactor: Replace Baidu Translation with Youdao Translation to eliminate configuration steps; optimize translation experience; add missing dependency prompts instead of causing program errors.Optimize the experience of switching between voice mode and setting global reply mode.

* Refactor: Remove unused files and dependencies in the project.

* Feature: Add Youdao translation service to provide more comprehensive translation support.

* Refactor: Optimize translation experience

* Refactor: Optimize translation experience

* Feature: Add functionality of keyword search command

* Feature: Add functionality of keyword search command.

* Refactor: Remove redundant code

* Add: Add feature to support randomly selecting roles for Azure voice. Refactor the code to support existing voice services for the ‘greeting’ feature. Fix the display issue of Azure voice role selection on the Guoba panel.

* Refactor: Remove redundant code

* Refactor: Improve the function of setting global voice roles and viewing role lists. Now you can set default roles for each voice service separately or view the supported role list.

* Refactor: Remove redundant code

* Feature: Add new function to support random character dialogues in all voice modes, add the ability to view the current user’s reply settings, and improve related functions in the global settings.

* Refactor: Add compatibility directive for viewing reply settings feature

* Feature: support adding QQ number to blacklist/whitelist

* fix: 处理全局设置指令被上下班指令占用的问题

* fix: 处理全局设置指令被上下班指令占用的问题

---------

Co-authored-by: Sean <1519059137@qq.com>
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-06-05 11:40:10 +08:00
Maitaozi
7007cacf6f
临时解决QQ频道、KOOK异常 (#441)
利用cache块隔离,临时解决获取不到e.group函数时自动跳过报错并继续执行
2023-06-05 11:38:37 +08:00
kae_mihara
220a3f155d
增加了“最新词云”功能 (#465)
* 增加了"最新词云"功能

* fix bug

* fix bug...

* fix bug......
2023-06-05 11:38:03 +08:00
K2Lin
c00b6d85d2
Fix Chat reset (#461) 2023-06-05 11:36:13 +08:00
ikechan8370
a46d6d850b fix: remove 垃圾代码 2023-06-02 19:39:04 +08:00
ikechan8370
5c7d85efd0 fix: 删除必应无token的提示因为不需要token了 2023-06-02 13:41:54 +08:00
ikechan8370
cecb16ee62
Update README.md 2023-06-02 13:28:07 +08:00
ikechan8370
9b54980ec0
Update README.md 2023-05-31 13:54:41 +08:00
ikechan8370
0efc67f522 fix: 微软能不能少报一些错啊 2023-05-30 17:12:46 +08:00
ikechan8370
9a8db9577a fix: 画图重试5次 2023-05-30 16:35:36 +08:00
ikechan8370
f2f77235b1 fix: 画图画完拿结果503处理 2023-05-30 16:29:08 +08:00
ikechan8370
c7a85baa4e Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-05-29 00:52:10 +08:00
ikechan8370
dc587cb164 fix: 无关紧要的修改 2023-05-29 00:52:04 +08:00
ikechan8370
cab59f0629
Update README.md 2023-05-29 00:43:15 +08:00
ikechan8370
455f0e8a92 fix: 加回锅巴的模型选项。gpt-4可以直接填 2023-05-29 00:35:15 +08:00
ikechan8370
3de9ca9c49 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-05-25 22:33:40 +08:00
ikechan8370
c91791ad21 fix: claude空@ 2023-05-25 22:33:08 +08:00
HalcyonAlcedo
2e8b59bb06
feat: 后台面板更新 (#448)
* 修复后台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检查

* 更新后台配置项

* 修复错误的文本描述

* 更新后台页面

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

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-05-25 19:07:19 +08:00
ikechan8370
375fad8a20 feat: 必应无需token即可进行对话(max20->5) 2023-05-25 18:54:55 +08:00
ikechan8370
3c437ddfc5 fix: 调整sydney token过期方式;画图调整增加成功概率 2023-05-24 21:00:36 +08:00
ikechan8370
cc78143c0e
fix: 更换Sydney接口 2023-05-23 10:42:14 +08:00
ikechan8370
758aeb67a2 fix: 开启内容生成会爆token的问题 2023-05-21 18:54:14 +08:00
ikechan8370
d88550db39
fix: syntax error 2023-05-21 18:47:49 +08:00
ElaineOwO
ea5c451355
Update management.js (#431) 2023-05-21 17:42:31 +08:00
Sean Murphy
f20248a805
移除axios依赖,替换百度翻译为有道翻译。指令表支持关键词筛选。 (#434)
* feat: add support for ‘greeting’ and ‘global reply mode’ commands, improve variable naming and remove unnecessary backend output.

* feat: Add support for black and white lists, global reply mode and voice role settings, private chat switch, and active greeting configuration. Refactor some variable names and comment out redundant code for better readability and reduced backend output.

* feat: 为新功能完善了帮助面板

* docs: 完善了‘打招呼’的帮助说明

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* refactor: Remove redundant log output.

* Refactor: optimize code logic

* Fix: 修复绘图指令表被抢指令的bug。

* Refactor:1. Add support for automatically translating replies to Japanese and generating voice messages in VITS voice mode (please monitor remaining quota after enabling). 2. Add translation function. 3. Add emotion configuration for Azure voice mode, allowing the robot to select appropriate emotional styles for replies.

* Refactor:Handle the issue of exceeding character setting limit caused by adding emotion configuration.

* Fix: fix bugs

* Refactor: Added error feedback to translation service

* Refactor: Added support for viewing the list of supported roles for each language mode, and fixed some bugs in the emotion switching feature of the auzre mode.

* Refactor: Optimized some command feedback and added owner restriction to chat record export function.

* Refactor: Optimized feedback when viewing role list to avoid excessive messages.

* Refactor: Optimized feedback when configuring multi-emotion mode.

* Feature: Added help instructions for translation feature.

* chore: Adjust help instructions for mood settings

* Fix: Fixed issue where only first line of multi-line replies were being read and Azure voice was pronouncing punctuation marks.

* Fix: Fixed bug where switching to Azure voice mode prompted for missing key and restricted ability to view voice role list to only when in voice mode.

* Refactor: Add image OCR function and support translation for both quoted text and image.

* fix: Fix issue with error caused by non-image input.

* Refactor: Optimize code to filter emojis that cannot be displayed properly in claude mode.

* Refactor: Optimize some code structures.

* fix: Fix the bug of returning only one result when entering multiple lines of text on Windows system.

* Refactor: Optimize code logic for better user experience

* Refactor: Fix the conflict issue with other plugin translation commands

* Refactor: Replace Baidu Translation with Youdao Translation to eliminate configuration steps; optimize translation experience; add missing dependency prompts instead of causing program errors.Optimize the experience of switching between voice mode and setting global reply mode.

* Refactor: Remove unused files and dependencies in the project.

* Feature: Add Youdao translation service to provide more comprehensive translation support.

* Refactor: Optimize translation experience

* Refactor: Optimize translation experience

* Feature: Add functionality of keyword search command

* Feature: Add functionality of keyword search command.

* Refactor: Remove redundant code

---------

Co-authored-by: Sean <1519059137@qq.com>
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-05-18 18:03:43 +08:00
HalcyonAlcedo
82b83bf015
Feat:Sydney模式添加内容生成支持 (#420)
* 修复后台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检查

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-05-18 15:00:26 +08:00
ikechan8370
6551f11434 fix: 开启真at后非yunzai环境报错 2023-05-17 17:51:26 +08:00
ikechan8370
6a7328a36a
Update README.md 2023-05-14 23:47:18 +08:00
ikechan8370
15f579aab8 fix: 修复Poe formkey失效的问题 2023-05-14 13:24:24 +08:00
ikechan8370
1a94d92943 fix: poe添加proxy支持 2023-05-14 12:47:20 +08:00
ikechan8370
63f8629037 fix: claude增加debug模式;poe添加proxy支持 2023-05-14 12:35:56 +08:00
ikechan8370
73e6dc43bc fix: #claude开启新对话被#claude抢走的问题 2023-05-12 20:37:03 +08:00
ikechan8370
b4dcfcb42a fix: update version 2023-05-12 20:31:40 +08:00
ikechan8370
d4a8c270af
docs: README.md 2023-05-12 20:30:54 +08:00
ikechan8370
3f42c05388 fix: 添加一个报错提示 2023-05-12 20:17:03 +08:00
ikechan8370
926f07c8e9 feat: 添加星火支持(beta) 2023-05-12 20:11:08 +08:00
HalcyonAlcedo
76f0328a8e
Fix:修复Live2D的错误,重构Live2D系统 (#410)
* 修复后台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

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-05-11 17:46:15 +08:00
ikechan8370
2bf3a636a6 fix: 微调Bing画图 2023-05-11 17:23:59 +08:00
ifeif
fde029cd91
小优化 (#408) 2023-05-07 22:32:57 +08:00
ikechan8370
e47f18a5aa
fix: add headers for refresh token 2023-05-06 01:11:19 +08:00
ikechan8370
6485d7a93e fix: update version 2023-05-05 21:04:55 +08:00
ikechan8370
fe42df5928 feat: 查看API余额功能;修复频道和部分情况下无法读取群信息时的报错 2023-05-05 21:04:32 +08:00
ifeif
bda0431714
修复文本和语音重复发送的问题 (#400)
* 修复文本和语音重复发送的问题

* 修复提示“你没有配置转语音API哦”的问题

* 新增:Bing对话达到上限时自动关闭对话

* 优化

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-05-04 22:58:40 +08:00
Sean Murphy
b687d45897
为azure语音模式添加说话风格配置,支持vits语音模式中文回答转日语语音输出,添加翻译功能,支持指令切换语音模式,支持查看当前语音模式下的支持角色列表 (#404)
* feat: add support for ‘greeting’ and ‘global reply mode’ commands, improve variable naming and remove unnecessary backend output.

* feat: Add support for black and white lists, global reply mode and voice role settings, private chat switch, and active greeting configuration. Refactor some variable names and comment out redundant code for better readability and reduced backend output.

* feat: 为新功能完善了帮助面板

* docs: 完善了‘打招呼’的帮助说明

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* refactor: Remove redundant log output.

* Refactor: optimize code logic

* Fix: 修复绘图指令表被抢指令的bug。

* Refactor:1. Add support for automatically translating replies to Japanese and generating voice messages in VITS voice mode (please monitor remaining quota after enabling). 2. Add translation function. 3. Add emotion configuration for Azure voice mode, allowing the robot to select appropriate emotional styles for replies.

* Refactor:Handle the issue of exceeding character setting limit caused by adding emotion configuration.

* Fix: fix bugs

* Refactor: Added error feedback to translation service

* Refactor: Added support for viewing the list of supported roles for each language mode, and fixed some bugs in the emotion switching feature of the auzre mode.

* Refactor: Optimized some command feedback and added owner restriction to chat record export function.

* Refactor: Optimized feedback when viewing role list to avoid excessive messages.

* Refactor: Optimized feedback when configuring multi-emotion mode.

* Feature: Added help instructions for translation feature.

* chore: Adjust help instructions for mood settings

* Fix: Fixed issue where only first line of multi-line replies were being read and Azure voice was pronouncing punctuation marks.

* Fix: Fixed bug where switching to Azure voice mode prompted for missing key and restricted ability to view voice role list to only when in voice mode.

---------

Co-authored-by: Sean <1519059137@qq.com>
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-05-04 22:55:49 +08:00
ikechan8370
bb90c3c3e7 fix: 优化slack对话拉取机制,避免过长对话导致的maxContentLength size of -1 exceeded错误 2023-05-04 16:54:00 +08:00
ikechan8370
30aa32d5e9
Update README.md (#401) 2023-05-02 17:19:21 +08:00
葛胤池
76d261666a fix: 增加新版本voicevox的新speakers 2023-04-29 19:16:54 +08:00
Err0rCM
0c5a5e8eb8
有关私聊影响其他功能体感的问题 (#387)
#369 关于此issue的问题
2023-04-29 18:46:51 +08:00
2ndelement
6267d2d842
在新的多TTS源模式下添加了VoiceVox源 (#381)
* feat: 添加基于voicevox语音支持

* fix: 配置里添加voicevox语音源

* fix: 切换语音模式对各种语言源提示错误

* fix: 修正voicevox角色风格设置问题

* fix: 修改角色性格切换问题

* fix: 解决角色性格切换问题

* fix 换源分支少打个break(java17-user是这样的)

* fix: 支持云转码的一些调整

---------

Co-authored-by: 葛胤池 <geyinchi@buaa.edu.cn>
2023-04-29 18:45:33 +08:00
葛胤池
d3bd7be722 Merge branch 'temp' into v2 2023-04-29 18:35:47 +08:00
葛胤池
1454917cad fix: 调整以支持云转码 2023-04-29 18:27:57 +08:00
HalcyonAlcedo
5099ae9d87
feat: 后台新增Azure语音配置项 (#383)
* 修复后台API反代地址未能正确显示的问题

* 更新渲染页面配置

* 添加个人聊天模式配置

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

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

* 修复bug

* 添加Live2D

* 修复渲染页面错误

* 修复渲染传入值

* 更新渲染

* 修复图表渲染bug

* 调整live2d模型大小

* 修复live2d无法关闭问题

* 修复错误的传值

* 修复ai命名

* 更新渲染

* 添加用户独立设定

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

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

* 修复用户数据缺失问题

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

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

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

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

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

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

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

* 更新README

* Update README.md

* 更新渲染

* 更新渲染页面

* 添加版本信息

* 遗漏参数

* 丢失引用

* 补充路由

* 添加云转码功能

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

* 云转码提示

* 修复图片渲染出错

* 云转码支持发送Buffer

* 添加云转码模式支持

* 更新描述

* 更新后台渲染页面

* 更新配置

* 更新渲染页面

* 添加云渲染

* 修复错误的接口调用

* 修复遗漏的数据转换

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

* 更新后台配置

* 更新渲染页面

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

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-04-29 17:24:33 +08:00
ikechan8370
eb6c25d75d
fix: 修复sydney设定抱歉的问题 2023-04-25 10:28:32 +08:00
127Wzc
06b26ab580
fix:修复对群友@时 昵称中含空格 导致一部分昵称被统计 (#384)
优化:
1.字典在导入nodejieba时初始化一次即可
修复:
1.通过qq消息对象中message对象的type类型直接过滤出文本内容
2023-04-24 23:58:36 +08:00
2ndelement
0daecc2edb
Merge branch 'v2' into v2 2023-04-23 23:39:58 +08:00
ikechan8370
9e4049181a fix: 结束对话指令改为(结束|新开|摧毁|毁灭|完结)对话 2023-04-23 21:09:11 +08:00
ikechan8370
d5e3d52d43 fix: 适配无oicq&icqq;删除存储的azure语音 2023-04-23 21:01:03 +08:00
ikechan8370
1bfb4d7d6b fix: 修改锅巴提示 2023-04-23 15:34:21 +08:00
ikechan8370
1f50e1b7a5 fix: azure语音云转码 2023-04-23 15:26:15 +08:00
ikechan8370
2cafdcaa82 fix: azure下云转码适配 2023-04-23 14:51:02 +08:00
Xcating
49af9dad80
修改指令触发方式 (#382) 2023-04-23 13:58:35 +08:00
2ndelement
cb9f0b2773
fix 换源分支少打个break(java17-user是这样的) 2023-04-23 02:40:33 +08:00
2ndelement
78a99801e7 fix: 解决角色性格切换问题 2023-04-23 02:01:36 +08:00
2ndelement
4a5407502a fix: 修改角色性格切换问题 2023-04-23 01:55:56 +08:00
2ndelement
06495c3c59 fix: 修正voicevox角色风格设置问题 2023-04-23 01:44:43 +08:00
2ndelement
68ef2d104f fix: 切换语音模式对各种语言源提示错误 2023-04-23 01:34:51 +08:00
2ndelement
8baef8b579 fix: 配置里添加voicevox语音源 2023-04-23 01:26:13 +08:00
2ndelement
94c44068a4 feat: 添加基于voicevox语音支持 2023-04-23 01:19:56 +08:00
ikechan8370
a714c21ffb fix: azure默认角色bug 2023-04-22 23:01:57 +08:00
ikechan8370
cf992bbc2c feat: 添加Azure语音支持 2023-04-22 22:54:03 +08:00
ikechan8370
20f6cd5390 fix: 词云增加一些筛选避免太过零碎 2023-04-22 20:09:54 +08:00
ikechan8370
aba80a5ddb fix: add version 2023-04-22 18:08:03 +08:00
ikechan8370
7ae248e5c4 fix: 语音云转码完善file和url模式。 2023-04-22 18:07:46 +08:00
HalcyonAlcedo
49d8dce984
Feat: 新增云转码模式选择 (#380)
* 修复后台API反代地址未能正确显示的问题

* 更新渲染页面配置

* 添加个人聊天模式配置

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

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

* 修复bug

* 添加Live2D

* 修复渲染页面错误

* 修复渲染传入值

* 更新渲染

* 修复图表渲染bug

* 调整live2d模型大小

* 修复live2d无法关闭问题

* 修复错误的传值

* 修复ai命名

* 更新渲染

* 添加用户独立设定

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

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

* 修复用户数据缺失问题

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

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

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

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

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

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

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

* 更新README

* Update README.md

* 更新渲染

* 更新渲染页面

* 添加版本信息

* 遗漏参数

* 丢失引用

* 补充路由

* 添加云转码功能

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

* 云转码提示

* 修复图片渲染出错

* 云转码支持发送Buffer

* 添加云转码模式支持

* 更新描述

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-04-22 17:29:23 +08:00
HalcyonAlcedo
55f060dc5f
Feat: 添加语音云转码功能,系统优化和故障修复 (#378)
* 修复后台API反代地址未能正确显示的问题

* 更新渲染页面配置

* 添加个人聊天模式配置

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

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

* 修复bug

* 添加Live2D

* 修复渲染页面错误

* 修复渲染传入值

* 更新渲染

* 修复图表渲染bug

* 调整live2d模型大小

* 修复live2d无法关闭问题

* 修复错误的传值

* 修复ai命名

* 更新渲染

* 添加用户独立设定

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

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

* 修复用户数据缺失问题

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

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

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

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

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

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

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

* 更新README

* Update README.md

* 更新渲染

* 更新渲染页面

* 添加版本信息

* 遗漏参数

* 丢失引用

* 补充路由

* 添加云转码功能

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

* 云转码提示

* 修复图片渲染出错
2023-04-21 23:36:25 +08:00
ikechan8370
26b4534cfb fix: 使用不存在的设定的bug 2023-04-21 15:02:49 +08:00
ikechan8370
c35c3a66ce fix: node-rs jieba error 2023-04-21 12:23:46 +08:00
ikechan8370
db72462b8e chore: change tokenizer to @node-rs/jieba 2023-04-20 22:15:55 +08:00
ikechan8370
cd228128ba fix: unknown 2023-04-20 19:18:26 +08:00
ikechan8370
5ded004538 fix: cd 2023-04-20 18:03:53 +08:00
ikechan8370
21fc4cbe45 fix: new group or member wordcloud bug 2023-04-20 18:01:51 +08:00
ikechan8370
1475768df8 fix: chat group history bug 2023-04-20 17:41:45 +08:00
ikechan8370
8342c583a5 fix: add some log 2023-04-20 17:26:01 +08:00
ikechan8370
719a810aca fix: import bug 2023-04-20 17:18:08 +08:00
ikechan8370
cee033dc5e fix: add npmrc env for nodejieba 2023-04-20 17:14:04 +08:00
ikechan8370
eab19833c7 fix: move nodejieba to optional dependencies 2023-04-20 17:11:39 +08:00
ikechan8370
e0d3395a77 fix: 依赖 2023-04-20 17:10:18 +08:00
ikechan8370
3cfbe9eae7 feat: 乱七八糟的的统计词云 2023-04-20 17:07:33 +08:00
ikechan8370
7f773dcfc4 fix: 调整claude无响应重试时间 2023-04-20 13:37:42 +08:00
ikechan8370
a3ef75cdcc feat: slack支持指定频道以便共享claude机器人 2023-04-20 13:08:30 +08:00
ikechan8370
74f4b641e4
Fix: uploadRecord.js 2023-04-20 00:32:42 +08:00
ikechan8370
f93f9ea0bb
fix: add node silk import error log 2023-04-20 00:28:19 +08:00
ikechan8370
a3b6af2851 fix: update version 2023-04-19 23:42:55 +08:00
Sean Murphy
2ce0a56ef6
Fix: 修复绘图指令表被抢指令的bug。 (#368)
* feat: add support for ‘greeting’ and ‘global reply mode’ commands, improve variable naming and remove unnecessary backend output.

* feat: Add support for black and white lists, global reply mode and voice role settings, private chat switch, and active greeting configuration. Refactor some variable names and comment out redundant code for better readability and reduced backend output.

* feat: 为新功能完善了帮助面板

* docs: 完善了‘打招呼’的帮助说明

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* refactor: Remove redundant log output.

* Refactor: optimize code logic

* Fix: 修复绘图指令表被抢指令的bug。

---------

Co-authored-by: Sean <1519059137@qq.com>
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-04-19 23:42:17 +08:00
鹤望兰
e7a0bcfee0
Update README.md (#375) 2023-04-19 23:41:53 +08:00
HalcyonAlcedo
73c88cce83
添加live2d模型自定义 (#374)
* 修复后台API反代地址未能正确显示的问题

* 更新渲染页面配置

* 添加个人聊天模式配置

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

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

* 修复bug

* 添加Live2D

* 修复渲染页面错误

* 修复渲染传入值

* 更新渲染

* 修复图表渲染bug

* 调整live2d模型大小

* 修复live2d无法关闭问题

* 修复错误的传值

* 修复ai命名

* 更新渲染

* 添加用户独立设定

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

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

* 修复用户数据缺失问题

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

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

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

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

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

* 修复传统渲染无法调用截图功能的问题
2023-04-19 23:40:52 +08:00
HalcyonAlcedo
36a51856c5
修复Miao-Yunzai无法使用新渲染的问题 (#372)
* 修复后台API反代地址未能正确显示的问题

* 更新渲染页面配置

* 添加个人聊天模式配置

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

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

* 修复bug

* 添加Live2D

* 修复渲染页面错误

* 修复渲染传入值

* 更新渲染

* 修复图表渲染bug

* 调整live2d模型大小

* 修复live2d无法关闭问题

* 修复错误的传值

* 修复ai命名

* 更新渲染

* 添加用户独立设定

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

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

* 修复用户数据缺失问题

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

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

* 修复受限token重试时不被排除的问题
2023-04-18 20:00:23 +08:00
ikechan8370
3e1fcad103 fix: 修改claude moderation鉴别方式 2023-04-18 19:37:39 +08:00
ikechan8370
aa040d4bf1 fix: 降低slack查询频率避免被限速 2023-04-18 15:51:54 +08:00
ikechan8370
edd705fbce fix: 必应妹! 2023-04-18 15:10:17 +08:00
HalcyonAlcedo
eb4628a4e8
更新个人设定 (#370)
* 修复后台API反代地址未能正确显示的问题

* 更新渲染页面配置

* 添加个人聊天模式配置

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

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

* 修复bug

* 添加Live2D

* 修复渲染页面错误

* 修复渲染传入值

* 更新渲染

* 修复图表渲染bug

* 调整live2d模型大小

* 修复live2d无法关闭问题

* 修复错误的传值

* 修复ai命名

* 更新渲染

* 添加用户独立设定

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

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

* 修复用户数据缺失问题

* 修复旧版本数据缺失问题
2023-04-18 14:50:15 +08:00
ikechan8370
6c5b31156a fix: 尝试修复userData.cast为null的情况 2023-04-18 13:29:35 +08:00
HalcyonAlcedo
e758b37d4a
添加SLACK CLAUDE配置 (#359)
* 修复后台API反代地址未能正确显示的问题

* 更新渲染页面配置

* 添加个人聊天模式配置

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

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

* 修复bug

* 添加Live2D

* 修复渲染页面错误

* 修复渲染传入值

* 更新渲染

* 修复图表渲染bug

* 调整live2d模型大小

* 修复live2d无法关闭问题

* 修复错误的传值

* 修复ai命名

* 更新渲染

* 添加用户独立设定
2023-04-18 12:41:20 +08:00
ikechan8370
40b72989e4 fix: 过长消息(多于4000)被slack夹断切分的问题 2023-04-17 21:26:04 +08:00
ikechan8370
fd06f8c21a chore: format code 2023-04-17 21:07:42 +08:00
ikechan8370
85e7e79883 fix: 尝试处理一下自动化插件导致的对话带上本月已发送x条消息 2023-04-17 17:17:38 +08:00
ikechan8370
5b94b49536 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-04-17 17:05:38 +08:00
ikechan8370
a804412c4d fix: 修复部分警告信息被输出的问题 2023-04-17 17:02:49 +08:00
Sean Murphy
351d89bd7c
新增查看插件指令表的功能,修复配置群聊黑白名单的bug,修复开启禁用私聊后仍可以使用#chat模式进行对话的bug (#366)
* feat: add support for ‘greeting’ and ‘global reply mode’ commands, improve variable naming and remove unnecessary backend output.

* feat: Add support for black and white lists, global reply mode and voice role settings, private chat switch, and active greeting configuration. Refactor some variable names and comment out redundant code for better readability and reduced backend output.

* feat: 为新功能完善了帮助面板

* docs: 完善了‘打招呼’的帮助说明

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* Commit Type: feat, bugfix

Add functionality to view plugin command table, fix bug in blacklist/whitelist, and fix bug where chat mode can still be used in private messaging when disabled.

* refactor: Remove redundant log output.

* Refactor: optimize code logic

---------

Co-authored-by: Sean <1519059137@qq.com>
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-04-17 14:31:16 +08:00
ikechan8370
2dc7cd5c29 feat: slack claude结束全部对话 2023-04-17 13:07:27 +08:00
ikechan8370
673fd88141 fix: 打招呼prompt不能热更新的问题 2023-04-17 12:58:40 +08:00
ikechan8370
06fd121950 feat: claude的设定 2023-04-17 12:48:01 +08:00
lori255
a2d903a2ae
fix: 修复Claude的用户ID固定导致无法邀请Claude的bug (#362)
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-04-16 20:33:14 +08:00
ikechan8370
08e95dc618 fix: 修复slask替换emoji后导致的复读bug 2023-04-16 19:32:21 +08:00
ikechan8370
1a96572bf7 fix: 修改版本号 2023-04-16 19:13:13 +08:00
ikechan8370
c1599e4f34 feat: 支持claude单人对话;注意:需要重新设置slack权限和配置插件 2023-04-16 19:12:56 +08:00
ikechan8370
3dee3ccec7 fix: 还是名片和昵称的恩怨情仇 2023-04-16 14:18:10 +08:00
ikechan8370
ba0c382886 fix: claude加入首条消息检测应对claude不说话的情况 2023-04-16 13:50:22 +08:00
ikechan8370
1e5010e9f1 fix: claude加入首条消息检测应对claude不说话的情况 2023-04-16 13:48:35 +08:00
ikechan8370
a68055c11d fix: 增加bot校验降低claude复读可能性 2023-04-16 13:42:39 +08:00
ikechan8370
aa91ddeed5 fix: 修改模式帮助 2023-04-16 13:30:03 +08:00
ikechan8370
bce9d00afa fix: nickname and card problem 2023-04-16 13:25:41 +08:00
ikechan8370
b66592d2fb Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-04-16 13:05:31 +08:00
ikechan8370
0451e19b09 fix: claude 结束对话提示 2023-04-16 13:05:24 +08:00
ikechan8370
70472464cf fix: 修复无群名片时at带上了昵称的问题 2023-04-16 00:48:32 +08:00
ikechan8370
7c36f9361e fix: 老模式的bug 2023-04-15 23:02:27 +08:00
ikechan8370
43ec7239b7
Update README.md 2023-04-15 21:11:48 +08:00
ikechan8370
7ef6051da8 feat: add support for Claude and Poe(WIP) 2023-04-15 21:00:34 +08:00
ikechan8370
a3a16bc5ff
fix: group admin page condition error 2023-04-15 11:28:58 +08:00
ikechan8370
c0aeceb4a4
Update README.md 2023-04-15 01:36:13 +08:00
hanhan258
2895d89fdb
修改错别字 (#353)
Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-04-14 21:45:17 +08:00
ikechan8370
414eb1b098 fix: format code 2023-04-14 21:44:06 +08:00
HalcyonAlcedo
2679206be9
更新后台配置内容 (#352)
* 添加chatgpt的新图片模式,临时处理切换api导致的对话异常

* 修改bing样式表

* 为图片添加外部页面缓存

* 为图片模式添加MathJax

* feat: add switch for qrcode

* 防止script攻击

* 修复网页模板错误

* 修复bing页面引用错误

* 缓存服务器异常时处理

* 添加默认配置加载

* 修复配置文件路径错误

* 删除重复的模板文件,修复二维码地址错误

* 修正图片渲染错误

* 修复引用渲染错误

* 二维码网址统一改为使用本地配置

* 添加关闭思考提示的配置项

* 修复在Windows上无法载入配置文件的问题

* 修复关闭qr的情况下渲染错误

* 改为使用base64传递返回数据

* 当异常过多时使用图片输出

* 添加锅巴面板配置支持

* 补充遗漏的默认配置

* 修复qr模式下引用未被传递的问题

* 修复未将引用数据传输给缓存服务器的问题

* 删除无用的bingTimeoutMs配置项

* 添加消息队列超时弹出

* 优化图片模式处理,解决对话队列卡住的问题

* 添加对图片ocr的支持

* 添加图片识别配置项

* 添加黑名单配置项

* 修复一些bug

* 修改锅巴配置格式和描述

* 传入数据也使用markdown

* 图片识别换行改为marked兼容

* 添加绘图CD配置项

* 独立render模块,添加图片回复引用

* 添加必应风格

* 修复上下文,修改bing样式

* 修复上下文

* 添加Sydney上下文支持

* 调整不同模式下的bing渲染颜色

* 修复样式

* 修复无法结束会话的问题

* fix: 更新版本号

* 修复无法结束对话的问题

* 向缓存服务器传送样式

* 为网址格式的配置添加验证

* 去除重复的Keyv删除,取消锅巴配置格式检查

* 闭合中断的代码块

* 试添加Sydney图片模式的情感显示

* 修复at不兼容

* 处理意外的markdown包裹和结构解析修复

* 修复markdown处理的顺序错误

* 兼容json换行

* 重写completeJSON和使用

* 修复换行格式异常

* 均衡BingToken使用

* 修复删除token的数组处理错误

* 修改token文字描述

* 创建本地缓存服务

* 修复首次使用无法添加bingtoken的问题

* 修复意外的删除格式问题,添加查看token功能

* 修复路由错误,暂时固定ip测试

* 恢复引用功能

* 更新渲染页面

* 更换缓存目录

* 清除调试用消息

* 调整屏幕分辨率

* 使用服务器生成的访问地址

* 改为使用api获取公网ip

* 修复引用显示

* 添加依赖需求

* 更新渲染页面和渲染api

* 修复渲染页面错误

* 修复建议字符串切割,添加帮助路由

* 添加内容中图片数据获取功能

* 试修复suggestbug

* 修复图片导致服务器卡死的问题

* 暂时禁用图片

* 尝试恢复图片

* 添加链接图片识别

* 替换掉request

* 修复可能的responseUrls空值

* 优化格式

* 更新渲染页面

* 尝试新的引用索引

* 取消渲染时旧的策略

* 更新帮助页面

* 修复帮助路由

* 修复渲染页面错误

* 修复错误的正则

* 修改系统api服务

* 添加配置项

* 将新渲染方式加入配置并还原原渲染方式,进行并存

* 暂时取消端口设置功能

* 重新开启端口设置

* 修复旧渲染引用

* 更新帮助样式

* 更新帮助,增强功能

* 有cacheHost的情况下不再附带端口号

* 添加渲染图片的宽度设置

* 添加渲染页面宽度调整,修bug

* 修复二维码不显示

* 添加第三方渲染支持

* 修复一些渲染页面问题

* 更新渲染页面

* 修正错误的变量调用

* 添加新渲染模式bot命名

* 修复空消息问题

* 撤销之前的修复,使用新方法修复

* 修复返回空页面问题

* 尝试不依赖网络获取外网地址

* 修bug,初步创建管理系统

* 依赖名写错了

* 修复错误的异步

* 修正错误的配置调用

* 放弃本机设置的获取方案,对服务器获取多半失效

* 添加配置页面接口

* 更新渲染页面

* 添加依赖

* 修复bug

* 移除windows性能显示,更换依赖

* 添加依赖

* 修复图片异常时不反回文字而是直接报错的问题

* 修改必应token记录和均衡方法,更新渲染页面

* 修复错误

* 修复bug,更新渲染页面

* 更新渲染

* 修复ip错误

* 完善配置页面

* 渲染页面错误修复

* 更新版本号

* 只获取一次有效ip

* 修复渲染页面bug

* 删除旧依赖

* 优化用户系统

* 修复登录数据错误

* 修复用户密码创建失败问题

* 限制密码私聊发送

* 修复数据获取异常bug

* 修复用户数据获取错误

* 修复渲染页面错误

* 用户清除缓存支持

* 添加用户配置功能

* 修复错误

* 修复用户缓存读取错误

* 修改服务的错误提示方式

* 配置管理员路由引导

* 修复管理员和用户路由错误

* 修复错误的文件删除函数

* 更新渲染页面

* 暂时还原数据获取方法

* 修复未注册账号无法生成图片的问题

* 修复index报错

* 更新渲染

* 修复渲染错误,异常token给3次机会

* 更新渲染页面

* 默认获取用户和管理后台地址只能通过私聊获取

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
Co-authored-by: Err0rCM <68117733+Err0rCM@users.noreply.github.com>
2023-04-14 21:10:27 +08:00
HalcyonAlcedo
adae071091
修复index错误 (#346)
* 使用chatgpt-api自带的超时逻辑,文字过多时启动切换到图片输出防止被吞

* Update chat.js

* 添加Bing专用的图片输出样式

* 添加chatgpt的新图片模式,临时处理切换api导致的对话异常

* 修改bing样式表

* 为图片添加外部页面缓存

* 为图片模式添加MathJax

* feat: add switch for qrcode

* 防止script攻击

* 修复网页模板错误

* 修复bing页面引用错误

* 缓存服务器异常时处理

* 添加默认配置加载

* 修复配置文件路径错误

* 删除重复的模板文件,修复二维码地址错误

* 修正图片渲染错误

* 修复引用渲染错误

* 二维码网址统一改为使用本地配置

* 添加关闭思考提示的配置项

* 修复在Windows上无法载入配置文件的问题

* 修复关闭qr的情况下渲染错误

* 改为使用base64传递返回数据

* 当异常过多时使用图片输出

* 添加锅巴面板配置支持

* 补充遗漏的默认配置

* 修复qr模式下引用未被传递的问题

* 修复未将引用数据传输给缓存服务器的问题

* 删除无用的bingTimeoutMs配置项

* 添加消息队列超时弹出

* 优化图片模式处理,解决对话队列卡住的问题

* 添加对图片ocr的支持

* 添加图片识别配置项

* 添加黑名单配置项

* 修复一些bug

* 修改锅巴配置格式和描述

* 传入数据也使用markdown

* 图片识别换行改为marked兼容

* 添加绘图CD配置项

* 独立render模块,添加图片回复引用

* 添加必应风格

* 修复上下文,修改bing样式

* 修复上下文

* 添加Sydney上下文支持

* 调整不同模式下的bing渲染颜色

* 修复样式

* 修复无法结束会话的问题

* fix: 更新版本号

* 修复无法结束对话的问题

* 向缓存服务器传送样式

* 为网址格式的配置添加验证

* 去除重复的Keyv删除,取消锅巴配置格式检查

* 闭合中断的代码块

* 试添加Sydney图片模式的情感显示

* 修复at不兼容

* 处理意外的markdown包裹和结构解析修复

* 修复markdown处理的顺序错误

* 兼容json换行

* 重写completeJSON和使用

* 修复换行格式异常

* 均衡BingToken使用

* 修复删除token的数组处理错误

* 修改token文字描述

* 创建本地缓存服务

* 修复首次使用无法添加bingtoken的问题

* 修复意外的删除格式问题,添加查看token功能

* 修复路由错误,暂时固定ip测试

* 恢复引用功能

* 更新渲染页面

* 更换缓存目录

* 清除调试用消息

* 调整屏幕分辨率

* 使用服务器生成的访问地址

* 改为使用api获取公网ip

* 修复引用显示

* 添加依赖需求

* 更新渲染页面和渲染api

* 修复渲染页面错误

* 修复建议字符串切割,添加帮助路由

* 添加内容中图片数据获取功能

* 试修复suggestbug

* 修复图片导致服务器卡死的问题

* 暂时禁用图片

* 尝试恢复图片

* 添加链接图片识别

* 替换掉request

* 修复可能的responseUrls空值

* 优化格式

* 更新渲染页面

* 尝试新的引用索引

* 取消渲染时旧的策略

* 更新帮助页面

* 修复帮助路由

* 修复渲染页面错误

* 修复错误的正则

* 修改系统api服务

* 添加配置项

* 将新渲染方式加入配置并还原原渲染方式,进行并存

* 暂时取消端口设置功能

* 重新开启端口设置

* 修复旧渲染引用

* 更新帮助样式

* 更新帮助,增强功能

* 有cacheHost的情况下不再附带端口号

* 添加渲染图片的宽度设置

* 添加渲染页面宽度调整,修bug

* 修复二维码不显示

* 添加第三方渲染支持

* 修复一些渲染页面问题

* 更新渲染页面

* 修正错误的变量调用

* 添加新渲染模式bot命名

* 修复空消息问题

* 撤销之前的修复,使用新方法修复

* 修复返回空页面问题

* 尝试不依赖网络获取外网地址

* 修bug,初步创建管理系统

* 依赖名写错了

* 修复错误的异步

* 修正错误的配置调用

* 放弃本机设置的获取方案,对服务器获取多半失效

* 添加配置页面接口

* 更新渲染页面

* 添加依赖

* 修复bug

* 移除windows性能显示,更换依赖

* 添加依赖

* 修复图片异常时不反回文字而是直接报错的问题

* 修改必应token记录和均衡方法,更新渲染页面

* 修复错误

* 修复bug,更新渲染页面

* 更新渲染

* 修复ip错误

* 完善配置页面

* 渲染页面错误修复

* 更新版本号

* 只获取一次有效ip

* 修复渲染页面bug

* 删除旧依赖

* 优化用户系统

* 修复登录数据错误

* 修复用户密码创建失败问题

* 限制密码私聊发送

* 修复数据获取异常bug

* 修复用户数据获取错误

* 修复渲染页面错误

* 用户清除缓存支持

* 添加用户配置功能

* 修复错误

* 修复用户缓存读取错误

* 修改服务的错误提示方式

* 配置管理员路由引导

* 修复管理员和用户路由错误

* 修复错误的文件删除函数

* 更新渲染页面

* 暂时还原数据获取方法

* 修复未注册账号无法生成图片的问题

* 修复index报错

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
Co-authored-by: Err0rCM <68117733+Err0rCM@users.noreply.github.com>
2023-04-14 00:16:58 +08:00
ifeif
b3122e5c04
新增:回复的内容过长时,自动转为文本模式。 (#344) 2023-04-14 00:16:35 +08:00
HalcyonAlcedo
9b9b69634e
添加用户管理功能 (#345)
* fix: remove queue element only in non-bing mode

* 使用chatgpt-api自带的超时逻辑,文字过多时启动切换到图片输出防止被吞

* Update chat.js

* 添加Bing专用的图片输出样式

* 添加chatgpt的新图片模式,临时处理切换api导致的对话异常

* 修改bing样式表

* 为图片添加外部页面缓存

* 为图片模式添加MathJax

* feat: add switch for qrcode

* 防止script攻击

* 修复网页模板错误

* 修复bing页面引用错误

* 缓存服务器异常时处理

* 添加默认配置加载

* 修复配置文件路径错误

* 删除重复的模板文件,修复二维码地址错误

* 修正图片渲染错误

* 修复引用渲染错误

* 二维码网址统一改为使用本地配置

* 添加关闭思考提示的配置项

* 修复在Windows上无法载入配置文件的问题

* 修复关闭qr的情况下渲染错误

* 改为使用base64传递返回数据

* 当异常过多时使用图片输出

* 添加锅巴面板配置支持

* 补充遗漏的默认配置

* 修复qr模式下引用未被传递的问题

* 修复未将引用数据传输给缓存服务器的问题

* 删除无用的bingTimeoutMs配置项

* 添加消息队列超时弹出

* 优化图片模式处理,解决对话队列卡住的问题

* 添加对图片ocr的支持

* 添加图片识别配置项

* 添加黑名单配置项

* 修复一些bug

* 修改锅巴配置格式和描述

* 传入数据也使用markdown

* 图片识别换行改为marked兼容

* 添加绘图CD配置项

* 独立render模块,添加图片回复引用

* 添加必应风格

* 修复上下文,修改bing样式

* 修复上下文

* 添加Sydney上下文支持

* 调整不同模式下的bing渲染颜色

* 修复样式

* 修复无法结束会话的问题

* fix: 更新版本号

* 修复无法结束对话的问题

* 向缓存服务器传送样式

* 为网址格式的配置添加验证

* 去除重复的Keyv删除,取消锅巴配置格式检查

* 闭合中断的代码块

* 试添加Sydney图片模式的情感显示

* 修复at不兼容

* 处理意外的markdown包裹和结构解析修复

* 修复markdown处理的顺序错误

* 兼容json换行

* 重写completeJSON和使用

* 修复换行格式异常

* 均衡BingToken使用

* 修复删除token的数组处理错误

* 修改token文字描述

* 创建本地缓存服务

* 修复首次使用无法添加bingtoken的问题

* 修复意外的删除格式问题,添加查看token功能

* 修复路由错误,暂时固定ip测试

* 恢复引用功能

* 更新渲染页面

* 更换缓存目录

* 清除调试用消息

* 调整屏幕分辨率

* 使用服务器生成的访问地址

* 改为使用api获取公网ip

* 修复引用显示

* 添加依赖需求

* 更新渲染页面和渲染api

* 修复渲染页面错误

* 修复建议字符串切割,添加帮助路由

* 添加内容中图片数据获取功能

* 试修复suggestbug

* 修复图片导致服务器卡死的问题

* 暂时禁用图片

* 尝试恢复图片

* 添加链接图片识别

* 替换掉request

* 修复可能的responseUrls空值

* 优化格式

* 更新渲染页面

* 尝试新的引用索引

* 取消渲染时旧的策略

* 更新帮助页面

* 修复帮助路由

* 修复渲染页面错误

* 修复错误的正则

* 修改系统api服务

* 添加配置项

* 将新渲染方式加入配置并还原原渲染方式,进行并存

* 暂时取消端口设置功能

* 重新开启端口设置

* 修复旧渲染引用

* 更新帮助样式

* 更新帮助,增强功能

* 有cacheHost的情况下不再附带端口号

* 添加渲染图片的宽度设置

* 添加渲染页面宽度调整,修bug

* 修复二维码不显示

* 添加第三方渲染支持

* 修复一些渲染页面问题

* 更新渲染页面

* 修正错误的变量调用

* 添加新渲染模式bot命名

* 修复空消息问题

* 撤销之前的修复,使用新方法修复

* 修复返回空页面问题

* 尝试不依赖网络获取外网地址

* 修bug,初步创建管理系统

* 依赖名写错了

* 修复错误的异步

* 修正错误的配置调用

* 放弃本机设置的获取方案,对服务器获取多半失效

* 添加配置页面接口

* 更新渲染页面

* 添加依赖

* 修复bug

* 移除windows性能显示,更换依赖

* 添加依赖

* 修复图片异常时不反回文字而是直接报错的问题

* 修改必应token记录和均衡方法,更新渲染页面

* 修复错误

* 修复bug,更新渲染页面

* 更新渲染

* 修复ip错误

* 完善配置页面

* 渲染页面错误修复

* 更新版本号

* 只获取一次有效ip

* 修复渲染页面bug

* 删除旧依赖

* 优化用户系统

* 修复登录数据错误

* 修复用户密码创建失败问题

* 限制密码私聊发送

* 修复数据获取异常bug

* 修复用户数据获取错误

* 修复渲染页面错误

* 用户清除缓存支持

* 添加用户配置功能

* 修复错误

* 修复用户缓存读取错误

* 修改服务的错误提示方式

* 配置管理员路由引导

* 修复管理员和用户路由错误

* 修复错误的文件删除函数

* 更新渲染页面

* 暂时还原数据获取方法

* 修复未注册账号无法生成图片的问题

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
Co-authored-by: Err0rCM <68117733+Err0rCM@users.noreply.github.com>
2023-04-13 22:47:20 +08:00
Sean Murphy
4b29e261a0
新增对群聊黑白名单和启禁用私聊的功能,添加对全局回复模式、语音角色和主动打招呼的指令配置。 (#341)
* feat: add support for ‘greeting’ and ‘global reply mode’ commands, improve variable naming and remove unnecessary backend output.

* feat: Add support for black and white lists, global reply mode and voice role settings, private chat switch, and active greeting configuration. Refactor some variable names and comment out redundant code for better readability and reduced backend output.

* feat: 为新功能完善了帮助面板

* docs: 完善了‘打招呼’的帮助说明

* feature:Add custom configuration for voice filtering regex.

---------

Co-authored-by: Sean <1519059137@qq.com>
2023-04-13 22:36:58 +08:00
lori255
11a62097f0
系统管理增加ipv6支持 (#342) 2023-04-12 23:19:15 +08:00
ifeif
98d414935e
修复了精准/平衡/创意模式下,给bing添加拓展资料后无法正常回复的问题 (#343) 2023-04-12 23:10:42 +08:00
ikechan8370
8bdbd623b3 fix: at都被挤到消息最前面的问题 2023-04-12 20:03:41 +08:00
ikechan8370
7bf5996dce fix: update version 2023-04-12 16:36:53 +08:00
HalcyonAlcedo
458b04c666
新增管理面板,重写必应token管理,错误修复 (#340)
* 修复引用转发,默认bing模式并发

* 开启stream增加稳定性

* fix: remove queue element only in non-bing mode

* 使用chatgpt-api自带的超时逻辑,文字过多时启动切换到图片输出防止被吞

* Update chat.js

* 添加Bing专用的图片输出样式

* 添加chatgpt的新图片模式,临时处理切换api导致的对话异常

* 修改bing样式表

* 为图片添加外部页面缓存

* 为图片模式添加MathJax

* feat: add switch for qrcode

* 防止script攻击

* 修复网页模板错误

* 修复bing页面引用错误

* 缓存服务器异常时处理

* 添加默认配置加载

* 修复配置文件路径错误

* 删除重复的模板文件,修复二维码地址错误

* 修正图片渲染错误

* 修复引用渲染错误

* 二维码网址统一改为使用本地配置

* 添加关闭思考提示的配置项

* 修复在Windows上无法载入配置文件的问题

* 修复关闭qr的情况下渲染错误

* 改为使用base64传递返回数据

* 当异常过多时使用图片输出

* 添加锅巴面板配置支持

* 补充遗漏的默认配置

* 修复qr模式下引用未被传递的问题

* 修复未将引用数据传输给缓存服务器的问题

* 删除无用的bingTimeoutMs配置项

* 添加消息队列超时弹出

* 优化图片模式处理,解决对话队列卡住的问题

* 添加对图片ocr的支持

* 添加图片识别配置项

* 添加黑名单配置项

* 修复一些bug

* 修改锅巴配置格式和描述

* 传入数据也使用markdown

* 图片识别换行改为marked兼容

* 添加绘图CD配置项

* 独立render模块,添加图片回复引用

* 添加必应风格

* 修复上下文,修改bing样式

* 修复上下文

* 添加Sydney上下文支持

* 调整不同模式下的bing渲染颜色

* 修复样式

* 修复无法结束会话的问题

* fix: 更新版本号

* 修复无法结束对话的问题

* 向缓存服务器传送样式

* 为网址格式的配置添加验证

* 去除重复的Keyv删除,取消锅巴配置格式检查

* 闭合中断的代码块

* 试添加Sydney图片模式的情感显示

* 修复at不兼容

* 处理意外的markdown包裹和结构解析修复

* 修复markdown处理的顺序错误

* 兼容json换行

* 重写completeJSON和使用

* 修复换行格式异常

* 均衡BingToken使用

* 修复删除token的数组处理错误

* 修改token文字描述

* 创建本地缓存服务

* 修复首次使用无法添加bingtoken的问题

* 修复意外的删除格式问题,添加查看token功能

* 修复路由错误,暂时固定ip测试

* 恢复引用功能

* 更新渲染页面

* 更换缓存目录

* 清除调试用消息

* 调整屏幕分辨率

* 使用服务器生成的访问地址

* 改为使用api获取公网ip

* 修复引用显示

* 添加依赖需求

* 更新渲染页面和渲染api

* 修复渲染页面错误

* 修复建议字符串切割,添加帮助路由

* 添加内容中图片数据获取功能

* 试修复suggestbug

* 修复图片导致服务器卡死的问题

* 暂时禁用图片

* 尝试恢复图片

* 添加链接图片识别

* 替换掉request

* 修复可能的responseUrls空值

* 优化格式

* 更新渲染页面

* 尝试新的引用索引

* 取消渲染时旧的策略

* 更新帮助页面

* 修复帮助路由

* 修复渲染页面错误

* 修复错误的正则

* 修改系统api服务

* 添加配置项

* 将新渲染方式加入配置并还原原渲染方式,进行并存

* 暂时取消端口设置功能

* 重新开启端口设置

* 修复旧渲染引用

* 更新帮助样式

* 更新帮助,增强功能

* 有cacheHost的情况下不再附带端口号

* 添加渲染图片的宽度设置

* 添加渲染页面宽度调整,修bug

* 修复二维码不显示

* 添加第三方渲染支持

* 修复一些渲染页面问题

* 更新渲染页面

* 修正错误的变量调用

* 添加新渲染模式bot命名

* 修复空消息问题

* 撤销之前的修复,使用新方法修复

* 修复返回空页面问题

* 尝试不依赖网络获取外网地址

* 修bug,初步创建管理系统

* 依赖名写错了

* 修复错误的异步

* 修正错误的配置调用

* 放弃本机设置的获取方案,对服务器获取多半失效

* 添加配置页面接口

* 更新渲染页面

* 添加依赖

* 修复bug

* 移除windows性能显示,更换依赖

* 添加依赖

* 修复图片异常时不反回文字而是直接报错的问题

* 修改必应token记录和均衡方法,更新渲染页面

* 修复错误

* 修复bug,更新渲染页面

* 更新渲染

* 修复ip错误

* 完善配置页面

* 渲染页面错误修复

* 更新版本号

* 只获取一次有效ip

* 修复渲染页面bug

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
Co-authored-by: Err0rCM <68117733+Err0rCM@users.noreply.github.com>
2023-04-12 16:35:41 +08:00
ikechan8370
c0a596a608 fix: move node-silk to optional dependencies to avoid various installation problems 2023-04-11 22:13:49 +08:00
ikechan8370
5119e17484 fix: 上下文忽略建议回复 2023-04-09 20:31:54 +08:00
ikechan8370
cfbad0972b fix: 修复at信息未被移除出prompt的问题 2023-04-09 19:36:35 +08:00
ikechan8370
93459ed94e feat: 尝试添加silk转码支持以避免缺少amr导致无法使用语音 2023-04-08 21:39:34 +08:00
ikechan8370
6b2cd446f9
fix: 减少必应token长度限制 2023-04-08 17:42:52 +08:00
Xcating
4c0a1852f6
修改了锅巴面板文案的部分问题🤔 (#324)
* 修改了部分锅巴配置的文案(统一了部分文案大小写与修复了句号结尾的不统一问题)。

* Revert "修改了部分锅巴配置的文案(统一了部分文案大小写与修复了句号结尾的不统一问题)。"

This reverts commit d62e53228f.

* 更改了锅巴文案结尾句号有些有,有些没有的问题

* Revert "更改了锅巴文案结尾句号有些有,有些没有的问题"

This reverts commit 33d0bb1869.

* 更改了锅巴面板文案有些有有些没有的问题
2023-04-08 01:17:30 +08:00
HalcyonAlcedo
a8240d51b4
修复空消息 (#323)
* 修复引用转发,默认bing模式并发

* 开启stream增加稳定性

* fix: remove queue element only in non-bing mode

* 使用chatgpt-api自带的超时逻辑,文字过多时启动切换到图片输出防止被吞

* Update chat.js

* 添加Bing专用的图片输出样式

* 添加chatgpt的新图片模式,临时处理切换api导致的对话异常

* 修改bing样式表

* 为图片添加外部页面缓存

* 为图片模式添加MathJax

* feat: add switch for qrcode

* 防止script攻击

* 修复网页模板错误

* 修复bing页面引用错误

* 缓存服务器异常时处理

* 添加默认配置加载

* 修复配置文件路径错误

* 删除重复的模板文件,修复二维码地址错误

* 修正图片渲染错误

* 修复引用渲染错误

* 二维码网址统一改为使用本地配置

* 添加关闭思考提示的配置项

* 修复在Windows上无法载入配置文件的问题

* 修复关闭qr的情况下渲染错误

* 改为使用base64传递返回数据

* 当异常过多时使用图片输出

* 添加锅巴面板配置支持

* 补充遗漏的默认配置

* 修复qr模式下引用未被传递的问题

* 修复未将引用数据传输给缓存服务器的问题

* 删除无用的bingTimeoutMs配置项

* 添加消息队列超时弹出

* 优化图片模式处理,解决对话队列卡住的问题

* 添加对图片ocr的支持

* 添加图片识别配置项

* 添加黑名单配置项

* 修复一些bug

* 修改锅巴配置格式和描述

* 传入数据也使用markdown

* 图片识别换行改为marked兼容

* 添加绘图CD配置项

* 独立render模块,添加图片回复引用

* 添加必应风格

* 修复上下文,修改bing样式

* 修复上下文

* 添加Sydney上下文支持

* 调整不同模式下的bing渲染颜色

* 修复样式

* 修复无法结束会话的问题

* fix: 更新版本号

* 修复无法结束对话的问题

* 向缓存服务器传送样式

* 为网址格式的配置添加验证

* 去除重复的Keyv删除,取消锅巴配置格式检查

* 闭合中断的代码块

* 试添加Sydney图片模式的情感显示

* 修复at不兼容

* 处理意外的markdown包裹和结构解析修复

* 修复markdown处理的顺序错误

* 兼容json换行

* 重写completeJSON和使用

* 修复换行格式异常

* 均衡BingToken使用

* 修复删除token的数组处理错误

* 修改token文字描述

* 创建本地缓存服务

* 修复首次使用无法添加bingtoken的问题

* 修复意外的删除格式问题,添加查看token功能

* 修复路由错误,暂时固定ip测试

* 恢复引用功能

* 更新渲染页面

* 更换缓存目录

* 清除调试用消息

* 调整屏幕分辨率

* 使用服务器生成的访问地址

* 改为使用api获取公网ip

* 修复引用显示

* 添加依赖需求

* 更新渲染页面和渲染api

* 修复渲染页面错误

* 修复建议字符串切割,添加帮助路由

* 添加内容中图片数据获取功能

* 试修复suggestbug

* 修复图片导致服务器卡死的问题

* 暂时禁用图片

* 尝试恢复图片

* 添加链接图片识别

* 替换掉request

* 修复可能的responseUrls空值

* 优化格式

* 更新渲染页面

* 尝试新的引用索引

* 取消渲染时旧的策略

* 更新帮助页面

* 修复帮助路由

* 修复渲染页面错误

* 修复错误的正则

* 修改系统api服务

* 添加配置项

* 将新渲染方式加入配置并还原原渲染方式,进行并存

* 暂时取消端口设置功能

* 重新开启端口设置

* 修复旧渲染引用

* 更新帮助样式

* 更新帮助,增强功能

* 有cacheHost的情况下不再附带端口号

* 添加渲染图片的宽度设置

* 添加渲染页面宽度调整,修bug

* 修复二维码不显示

* 添加第三方渲染支持

* 修复一些渲染页面问题

* 更新渲染页面

* 修正错误的变量调用

* 添加新渲染模式bot命名

* 修复空消息问题

* 撤销之前的修复,使用新方法修复

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
Co-authored-by: Err0rCM <68117733+Err0rCM@users.noreply.github.com>
2023-04-08 01:16:53 +08:00
HalcyonAlcedo
3b66f6d3f6
修复bug (#321) 2023-04-07 16:32:24 +08:00
HalcyonAlcedo
0a0cefe39c
新渲染模式配置完善和bug修复 (#318) 2023-04-07 10:24:31 +08:00
ikechan8370
f688b01816 chore: version tag 2023-04-06 23:53:17 +08:00
HalcyonAlcedo
0926009bb3
新的图片模式页面缓存和配套的API系统 (#315)
* 修复引用转发,默认bing模式并发

* 开启stream增加稳定性

* fix: remove queue element only in non-bing mode

* 使用chatgpt-api自带的超时逻辑,文字过多时启动切换到图片输出防止被吞

* Update chat.js

* 添加Bing专用的图片输出样式

* 添加chatgpt的新图片模式,临时处理切换api导致的对话异常

* 修改bing样式表

* 为图片添加外部页面缓存

* 为图片模式添加MathJax

* feat: add switch for qrcode

* 防止script攻击

* 修复网页模板错误

* 修复bing页面引用错误

* 缓存服务器异常时处理

* 添加默认配置加载

* 修复配置文件路径错误

* 删除重复的模板文件,修复二维码地址错误

* 修正图片渲染错误

* 修复引用渲染错误

* 二维码网址统一改为使用本地配置

* 添加关闭思考提示的配置项

* 修复在Windows上无法载入配置文件的问题

* 修复关闭qr的情况下渲染错误

* 改为使用base64传递返回数据

* 当异常过多时使用图片输出

* 添加锅巴面板配置支持

* 补充遗漏的默认配置

* 修复qr模式下引用未被传递的问题

* 修复未将引用数据传输给缓存服务器的问题

* 删除无用的bingTimeoutMs配置项

* 添加消息队列超时弹出

* 优化图片模式处理,解决对话队列卡住的问题

* 添加对图片ocr的支持

* 添加图片识别配置项

* 添加黑名单配置项

* 修复一些bug

* 修改锅巴配置格式和描述

* 传入数据也使用markdown

* 图片识别换行改为marked兼容

* 添加绘图CD配置项

* 独立render模块,添加图片回复引用

* 添加必应风格

* 修复上下文,修改bing样式

* 修复上下文

* 添加Sydney上下文支持

* 调整不同模式下的bing渲染颜色

* 修复样式

* 修复无法结束会话的问题

* fix: 更新版本号

* 修复无法结束对话的问题

* 向缓存服务器传送样式

* 为网址格式的配置添加验证

* 去除重复的Keyv删除,取消锅巴配置格式检查

* 闭合中断的代码块

* 试添加Sydney图片模式的情感显示

* 修复at不兼容

* 处理意外的markdown包裹和结构解析修复

* 修复markdown处理的顺序错误

* 兼容json换行

* 重写completeJSON和使用

* 修复换行格式异常

* 均衡BingToken使用

* 修复删除token的数组处理错误

* 修改token文字描述

* 创建本地缓存服务

* 修复首次使用无法添加bingtoken的问题

* 修复意外的删除格式问题,添加查看token功能

* 修复路由错误,暂时固定ip测试

* 恢复引用功能

* 更新渲染页面

* 更换缓存目录

* 清除调试用消息

* 调整屏幕分辨率

* 使用服务器生成的访问地址

* 改为使用api获取公网ip

* 修复引用显示

* 添加依赖需求

* 更新渲染页面和渲染api

* 修复渲染页面错误

* 修复建议字符串切割,添加帮助路由

* 添加内容中图片数据获取功能

* 试修复suggestbug

* 修复图片导致服务器卡死的问题

* 暂时禁用图片

* 尝试恢复图片

* 添加链接图片识别

* 替换掉request

* 修复可能的responseUrls空值

* 优化格式

* 更新渲染页面

* 尝试新的引用索引

* 取消渲染时旧的策略

* 更新帮助页面

* 修复帮助路由

* 修复渲染页面错误

* 修复错误的正则

* 修改系统api服务

* 添加配置项

* 将新渲染方式加入配置并还原原渲染方式,进行并存

* 暂时取消端口设置功能

* 重新开启端口设置

* 修复旧渲染引用

* 更新帮助样式

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-04-06 23:52:33 +08:00
ikechan8370
c469813711
Update README.md 2023-04-05 21:03:00 +08:00
ikechan8370
f8e741b0ca fix: 移除多余的依赖 2023-04-04 16:32:10 +08:00
ikechan8370
20f46717aa Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-04-04 16:09:14 +08:00
ikechan8370
ec82629238 fix: api3传输形式优化 2023-04-04 16:08:14 +08:00
ikechan8370
5350c9d4f3
Update README.md 2023-04-04 00:38:07 +08:00
ikechan8370
820cf76eaf feat: 画图支持代理 2023-04-03 21:14:07 +08:00
ikechan8370
93c286e240 fix: 未传入的主人昵称 2023-04-03 19:39:20 +08:00
ikechan8370
b4a8311acf fix: 未传入的主人昵称 2023-04-03 19:37:41 +08:00
ikechan8370
e343d54ea2 fix: 无response body的情况 2023-04-03 19:33:10 +08:00
ikechan8370
943ee5951b fix: bing绘图取消权限 2023-04-03 19:21:48 +08:00
ikechan8370
4bd6c8c7d8 fix: 优化一些错误提示和一些代码格式化 2023-04-03 16:41:18 +08:00
ikechan8370
c5d11efb74 fix: 修复新版主人认知导致自定义不生效的问题 2023-04-03 12:39:14 +08:00
ikechan8370
0d5ebc073f Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-04-03 12:31:20 +08:00
Sean Murphy
68bb1f221e
Chore: Optimize some code logic and add support for chat context in '锅巴面板' and 'chatgpt帮助' (#310)
* Optimized code logic and added support for chat context in '锅巴面板' and 'chatgpt帮助'

In this commit, I have optimized certain code logic to improve the performance of the application. Additionally, I have added support for chat context in croutons and help, which will enhance the user experience and make the chatbot more user-friendly. This feature will allow users to maintain a better understanding of the conversation flow and context, and will ultimately lead to more successful interactions with the chatbot.

* Update chat.js

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-04-03 11:11:18 +08:00
ikechan8370
af2b879f74 fix: 上传设定改名字无效的问题 2023-04-02 21:30:32 +08:00
ikechan8370
84eabee14d
Update README.md 2023-04-02 14:19:03 +08:00
ikechan8370
9e69a00c10 fix: 释放出无报错信息的情况 2023-04-02 13:56:42 +08:00
ikechan8370
486b89a5b3 docs: 更新部分文档;增加beta过期bing token移除 2023-04-02 13:52:14 +08:00
ikechan8370
fcc9691588 fix: 删除共享设定的笔误bug 2023-04-02 13:26:31 +08:00
ikechan8370
10bbbf4f64 fix: 修复对原生bing造成的影响 2023-04-02 13:10:00 +08:00
ikechan8370
95a4d7a69c feat: 通过降级messageType手段复活限流的账户 2023-04-02 12:08:48 +08:00
ikechan8370
14b4d3cdf4 fix: bing绘图重复发送的问题 2023-04-01 22:42:11 +08:00
ikechan8370
d6267e3f98 fix: 画图暂时改为只能主人 2023-04-01 22:03:39 +08:00
ikechan8370
fe0ca177f3 fix: 报错 2023-04-01 22:01:29 +08:00
ikechan8370
1336368bc3 fix: 报错 2023-04-01 22:00:38 +08:00
ikechan8370
98943bee9a fix: bing绘图(beta) 2023-04-01 21:58:04 +08:00
ikechan8370
da5adc0d10 fix: 增加实验性质的sydney反代,频繁throttle的用户可开启试试 2023-04-01 13:02:11 +08:00
ikechan8370
fd408586a8 fix: 修复多token功能带来的一些影响 2023-04-01 12:25:20 +08:00
HalcyonAlcedo
e93614ca35
修复多Token功能问题 (#303)
* 修复引用转发,默认bing模式并发

* 开启stream增加稳定性

* fix: remove queue element only in non-bing mode

* 使用chatgpt-api自带的超时逻辑,文字过多时启动切换到图片输出防止被吞

* Update chat.js

* 添加Bing专用的图片输出样式

* 添加chatgpt的新图片模式,临时处理切换api导致的对话异常

* 修改bing样式表

* 为图片添加外部页面缓存

* 为图片模式添加MathJax

* feat: add switch for qrcode

* 防止script攻击

* 修复网页模板错误

* 修复bing页面引用错误

* 缓存服务器异常时处理

* 添加默认配置加载

* 修复配置文件路径错误

* 删除重复的模板文件,修复二维码地址错误

* 修正图片渲染错误

* 修复引用渲染错误

* 二维码网址统一改为使用本地配置

* 添加关闭思考提示的配置项

* 修复在Windows上无法载入配置文件的问题

* 修复关闭qr的情况下渲染错误

* 改为使用base64传递返回数据

* 当异常过多时使用图片输出

* 添加锅巴面板配置支持

* 补充遗漏的默认配置

* 修复qr模式下引用未被传递的问题

* 修复未将引用数据传输给缓存服务器的问题

* 删除无用的bingTimeoutMs配置项

* 添加消息队列超时弹出

* 优化图片模式处理,解决对话队列卡住的问题

* 添加对图片ocr的支持

* 添加图片识别配置项

* 添加黑名单配置项

* 修复一些bug

* 修改锅巴配置格式和描述

* 传入数据也使用markdown

* 图片识别换行改为marked兼容

* 添加绘图CD配置项

* 独立render模块,添加图片回复引用

* 添加必应风格

* 修复上下文,修改bing样式

* 修复上下文

* 添加Sydney上下文支持

* 调整不同模式下的bing渲染颜色

* 修复样式

* 修复无法结束会话的问题

* fix: 更新版本号

* 修复无法结束对话的问题

* 向缓存服务器传送样式

* 为网址格式的配置添加验证

* 去除重复的Keyv删除,取消锅巴配置格式检查

* 闭合中断的代码块

* 试添加Sydney图片模式的情感显示

* 修复at不兼容

* 处理意外的markdown包裹和结构解析修复

* 修复markdown处理的顺序错误

* 兼容json换行

* 重写completeJSON和使用

* 修复换行格式异常

* 均衡BingToken使用

* 修复删除token的数组处理错误

* 修改token文字描述

* 修复首次使用无法添加bingtoken的问题

* 修复意外的删除格式问题,添加查看token功能

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-03-31 19:06:50 +08:00
ikechan8370
5b62667839 feat: 改用SydneyClient更准确地检测token 2023-03-31 13:52:53 +08:00
ikechan8370
df4ecc84ab fix: emoji regex fix 2023-03-31 13:48:13 +08:00
ikechan8370
b770aa9021 fix: 修复emoji正则 2023-03-31 11:59:52 +08:00
HalcyonAlcedo
8fb2615811
添加多必应token均衡支持 (#299) 2023-03-31 10:44:21 +08:00
ikechan8370
7d89849c88 fix: e not defined error 2023-03-31 00:24:43 +08:00
ikechan8370
12dc262dfc fix: 修复bing出错会导致对话丢失的问题(大概) 2023-03-30 20:54:58 +08:00
ikechan8370
f71f1d7ed7 fix: qq号格式问题 2023-03-30 20:34:35 +08:00
ikechan8370
9c3d1bc5e4 feat: 尝试把20条后溢出的对话自动塞到扩展后面 2023-03-30 17:19:18 +08:00
ikechan8370
019dc5e0c3 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-03-30 17:06:18 +08:00
ikechan8370
11735ead3b fix: 设定管理增加机器人qq的fallback 2023-03-30 17:06:04 +08:00
ikechan8370
914a01994b
Update README.md 2023-03-30 16:56:45 +08:00
ikechan8370
1f58ac5476 fix: remove test 2023-03-30 16:48:08 +08:00
ikechan8370
f368f4f040 fix: 优化qq表情适配 2023-03-30 12:12:28 +08:00
ikechan8370
bae27b7362 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-03-30 11:39:44 +08:00
ikechan8370
a4d8488a55 feat: API3支持event stream 2023-03-30 11:39:30 +08:00
HalcyonAlcedo
f21c3bee39
一些功能补正和增强 (#217)
* 修复引用转发,默认bing模式并发

* 开启stream增加稳定性

* fix: remove queue element only in non-bing mode

* 使用chatgpt-api自带的超时逻辑,文字过多时启动切换到图片输出防止被吞

* Update chat.js

* 添加Bing专用的图片输出样式

* 添加chatgpt的新图片模式,临时处理切换api导致的对话异常

* 修改bing样式表

* 为图片添加外部页面缓存

* 为图片模式添加MathJax

* feat: add switch for qrcode

* 防止script攻击

* 修复网页模板错误

* 修复bing页面引用错误

* 缓存服务器异常时处理

* 添加默认配置加载

* 修复配置文件路径错误

* 删除重复的模板文件,修复二维码地址错误

* 修正图片渲染错误

* 修复引用渲染错误

* 二维码网址统一改为使用本地配置

* 添加关闭思考提示的配置项

* 修复在Windows上无法载入配置文件的问题

* 修复关闭qr的情况下渲染错误

* 改为使用base64传递返回数据

* 当异常过多时使用图片输出

* 添加锅巴面板配置支持

* 补充遗漏的默认配置

* 修复qr模式下引用未被传递的问题

* 修复未将引用数据传输给缓存服务器的问题

* 删除无用的bingTimeoutMs配置项

* 添加消息队列超时弹出

* 优化图片模式处理,解决对话队列卡住的问题

* 添加对图片ocr的支持

* 添加图片识别配置项

* 添加黑名单配置项

* 修复一些bug

* 修改锅巴配置格式和描述

* 传入数据也使用markdown

* 图片识别换行改为marked兼容

* 添加绘图CD配置项

* 独立render模块,添加图片回复引用

* 添加必应风格

* 修复上下文,修改bing样式

* 修复上下文

* 添加Sydney上下文支持

* 调整不同模式下的bing渲染颜色

* 修复样式

* 修复无法结束会话的问题

* fix: 更新版本号

* 修复无法结束对话的问题

* 向缓存服务器传送样式

* 为网址格式的配置添加验证

* 去除重复的Keyv删除,取消锅巴配置格式检查

* 闭合中断的代码块

* 试添加Sydney图片模式的情感显示

* 修复at不兼容

* 处理意外的markdown包裹和结构解析修复

* 修复markdown处理的顺序错误

* 兼容json换行

---------

Co-authored-by: ikechan8370 <geyinchibuaa@gmail.com>
2023-03-30 00:17:02 +08:00
ikechan8370
cc785261eb fix: 聊天记录用户头像和昵称 2023-03-30 00:03:39 +08:00
ikechan8370
ea536c2e21 fix: 聊天记录用户头像和昵称 2023-03-30 00:01:54 +08:00
ikechan8370
407a2e1d66 fix: 查看他人聊天记录的bug 2023-03-29 23:59:40 +08:00
ikechan8370
d3fdaaa4b3 fix: 空聊天记录的bug 2023-03-29 23:52:55 +08:00
ikechan8370
fbfd105e0d feat: 聊天记录 2023-03-29 23:50:49 +08:00
ikechan8370
0755b54486 fix: 尝试修复错误直接对话没了的问题(不知道好使不) 2023-03-29 22:49:28 +08:00
ikechan8370
3121b0e463 fix: 增加配置项enforceMaster 2023-03-29 21:32:12 +08:00
ikechan8370
15a582abd5 fix: 修复私聊qq undefiend的问题 2023-03-29 20:55:59 +08:00
ikechan8370
1c1c2562ae fix: 支持了微软稀有的消息拆分cursor 2023-03-29 20:43:34 +08:00
ikechan8370
3bdfb15b0d fix: 未知原因的错误 2023-03-29 20:43:14 +08:00
ikechan8370
d3c9cbbdff fix: version 2023-03-29 19:42:42 +08:00
ikechan8370
58c2b24239 fix: 主人辨别beta 2023-03-29 19:42:22 +08:00
ikechan8370
20469346ec feat: 浏览设定增加翻页提示 2023-03-29 12:37:19 +08:00
ikechan8370
b110531135 fix: 修复pickMember问题 2023-03-29 12:04:46 +08:00
ikechan8370
54f68132f9 fix: 优化一些稳定性 2023-03-29 11:38:43 +08:00
ikechan8370
1563e49a25 fix: at模式下多接受了一个at信息的问题 2023-03-29 11:21:05 +08:00
ikechan8370
fadf9f6a8c fix: 对昨晚更新后遗症的修修补补;预览在线设定 2023-03-29 11:01:59 +08:00
ikechan8370
1d43de9ce0 fix: 删掉关于洗脑的东西,因为不需要了 2023-03-29 00:55:33 +08:00
ikechan8370
192beb2722 fix: sydney和自定义的无限续杯 2023-03-29 00:48:24 +08:00
ikechan8370
4b93b5edaf fix: 修复一个锅巴的笔误 2023-03-28 23:55:23 +08:00
ikechan8370
6da671e533 fix: 悉尼同样的抢救方式 2023-03-28 23:17:40 +08:00
ikechan8370
6de86db6f6 fix: 后续对话有时不传入内容的问题 2023-03-28 23:14:44 +08:00
ikechan8370
ef6605db2d fix: 补丁 2023-03-28 23:03:02 +08:00
ikechan8370
f4aaf5b0e4 fix: 大改bing patch策略beta 2023-03-28 22:59:46 +08:00
ikechan8370
b68cb41104 fix: 再次更换bing破解方式 2023-03-28 22:49:07 +08:00
ikechan8370
c57102fff1 fix: update version 2023-03-28 22:28:01 +08:00
ikechan8370
533dceb865 fix: 尝试了其他的bing破解方式 2023-03-28 22:27:40 +08:00
ikechan8370
d36b7c83bc
docs: 增加吹水群 2023-03-28 21:01:19 +08:00
ikechan8370
02d7aa0301 fix: 锅巴面板增加两个配置项 2023-03-28 20:07:58 +08:00
ikechan8370
cc2c561224 feat: qq表情和真的群聊at 2023-03-28 19:50:51 +08:00
ikechan8370
cae324f250 fix: 使用更清晰的报错信息 2023-03-28 16:35:28 +08:00
ikechan8370
b4f37b5339 fix: 删除上传的设定;一些设定共享的优化改进 2023-03-28 16:18:09 +08:00
ikechan8370
b11a653c51
Update README.md 2023-03-27 23:00:32 +08:00
ikechan8370
05f142d32c fix: 修正聊天的时间戳 2023-03-27 13:11:07 +08:00
ikechan8370
847a623c75 fix: 试图拿到更完整的群聊信息 2023-03-26 23:40:01 +08:00
ikechan8370
1c79ff00b7 feat: 改用调接口拿聊天记录,不用自己记录了 2023-03-26 23:23:37 +08:00
ikechan8370
3885527a7d fix: 单独提出监听对话以便赋予较高优先级 2023-03-26 22:58:51 +08:00
ikechan8370
ad62b53af4 fix: 自定义再系统消息中让他看聊天记录 2023-03-26 22:42:44 +08:00
ikechan8370
f1479f0e10 fix: 试图拯救浏览器模式,不行就弃了 2023-03-26 21:43:35 +08:00
ikechan8370
6f8eb1dd84 fix: version 2023-03-26 21:29:57 +08:00
ikechan8370
b6218a26ed Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-03-26 21:29:22 +08:00
ikechan8370
7d571df12a feat: add robot msg 2023-03-26 21:29:15 +08:00
时雨◎星空
00afb75bb5
隐藏日志,修改 segment 导入 (#287) 2023-03-26 21:28:14 +08:00
ikechan8370
6653188a8f feat: 群聊上下文记录功能beta 2023-03-26 18:40:12 +08:00
ikechan8370
d8999c77e6 fix: 修改上传设定锁的时间 2023-03-26 16:55:30 +08:00
ikechan8370
90a1f6a084 fix: 浏览设定页码 2023-03-26 16:27:33 +08:00
ikechan8370
bfc55df6a6
fix: 尝试支持设定分享和导入 (#286)
* fix: 尝试支持设定分享和导入

* fix: 设定分享和洗脑操作的帮助

* fix: 导入设定失败的提示

* fix: 允许覆盖修改

* fix: version
2023-03-26 16:15:15 +08:00
ikechan8370
07d1db0a2a
Update README.md 2023-03-25 21:07:04 +08:00
ikechan8370
c2d507ea91 fix: 忽略一样的表情包 2023-03-25 20:56:05 +08:00
ikechan8370
028a7c2c4a fix: emoji缓存 2023-03-25 20:53:34 +08:00
ikechan8370
d48748c0f5 Merge branch 'v2' of github.com:ikechan8370/chatgpt-plugin into v2 2023-03-25 20:23:08 +08:00
ikechan8370
f4a740a6a8 feat: emoji合成 2023-03-25 20:22:50 +08:00
ikechan8370
5c3ca4e9af
Create LICENSE (#284) 2023-03-25 19:35:16 +08:00
ikechan8370
3c62f2f5ed
Delete LICENSE 2023-03-25 19:31:48 +08:00
小飞
73689f4639
增加语音合成失败处理。 (#278) 2023-03-25 15:29:09 +08:00
203 changed files with 12740 additions and 15035 deletions

View file

@ -1,20 +0,0 @@
---
name: 功能请求(Feature request)
about: 为本项目提出一个新想法
title: ''
labels: ''
assignees: ''
---
**你的功能请求是否与某个问题有关?请描述。**
问题的清晰而简明的描述。
**描述你想要的解决方案**
你想要发生什么的清晰而简明的描述。
**描述你已经考虑的替代方案**
对任何替代解决方案或功能的清晰简明的描述。
**附加说明**
在此处添加有关功能请求的任何其他说明、屏幕截图或者引用。

View file

@ -1,45 +0,0 @@
---
name: 问题反馈
about: 提出bug解决问题并改进本项目
title: ''
labels: ''
assignees: ''
---
# 请确保提出问题前更新到最新版本!!!!!!!!
**请在提交issue前确认你已阅读了以下资料**
- 项目的readme文件
- 其他已有的Issue
如果你的问题已经在readme或其他Issue中得到解答我们很可能不会回复。请确保你的问题是一个新的问题。
## 问题描述
请在此处描述您遇到的问题,包括出现问题的环境、您试图实现的功能以及错误信息等。请尽可能详细,以便其他人可以在自己的环境中复制问题。
## 预期行为
请描述您期望系统在出现问题时应该做什么。
## 实际行为
请描述您实际看到的行为。
## 复制过程
请详细描述如何复制这个问题,包括所有必要的步骤、输入、任何错误信息以及输出。
## 环境
请提供您使用的任何相关信息,例如操作系统、版本、配置等。
## 可能的解决方案
如果您已经尝试了一些解决方案,请在此处描述这些解决方案,并说明是否有效。
## 附加信息
如果有任何其他信息,如日志、截图等,请在此处提供。

View file

@ -1,19 +0,0 @@
---
name: "tagged-release"
on:
push:
tags:
- "v*"
jobs:
tagged-release:
name: "Tagged Release"
runs-on: "ubuntu-latest"
steps:
# ...
- uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
prerelease: false

13
.gitignore vendored
View file

@ -1,7 +1,8 @@
config/*
!config/config.example.js
!config/config.example.json
!config/config.md
prompts/*
!prompts/.gitkeep
node_modules/
data/
utils/processors
utils/tools
utils/triggers
memory.md
resources/simple
memory.db

3
.npmrc
View file

@ -1 +1,2 @@
sharp_libvips_binary_host="https://registry.npmmirror.com/-/binary/sharp-libvips"
sharp_libvips_binary_host="https://registry.npmmirror.com/-/binary/sharp-libvips"
nodejieba_binary_host_mirror="https://npm.taobao.org/mirrors/nodejieba"

811
LICENSE
View file

@ -1,201 +1,674 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
1. Definitions.
Preamble
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
The precise terms and conditions for copying, distribution and
modification follow.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
TERMS AND CONDITIONS
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
0. Definitions.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
"This License" refers to version 3 of the GNU General Public License.
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
A "covered work" means either the unmodified Program or a work based
on the Program.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
1. Source Code.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
END OF TERMS AND CONDITIONS
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
APPENDIX: How to apply the Apache License to your work.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
Copyright [yyyy] [name of copyright owner]
The Corresponding Source for a work in source code form is that
same work.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
2. Basic Permissions.
http://www.apache.org/licenses/LICENSE-2.0
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View file

@ -1,36 +0,0 @@
## 本页面已过时
### Node.js >= 14 (并且 <18)时的安装方法
**如果不是 CentOS 7, RHEL 7, Ubuntu 18 请自行搜索并升级你的 Node.js 版本!**
**此教程是为了因 glibc 不支持升级 Node.js 的Linux发行版准备的。**
1. 进入 Yunzai 根目录
2. 安装依赖
```
pnpm install -w undici chatgpt showdown mathjax-node delay uuid remark strip-markdown node-fetch @waylaidwanderer/chatgpt-api keyv-file
```
**若使用API模式chatgpt的版本号注意要大于4.2.0**
若不使用浏览器模式,可以不安装`random puppeteer-extra-plugin-recaptcha puppeteer-extra puppeteer-extra-plugin-stealth`这几个
3. 克隆项目
```
git clone https://github.com/ikechan8370/chatgpt-plugin.git ./plugins/chatgpt-plugin
```
4. 修改配置
修改 Yunzai根目录/node_modules/.pnpm/chatgpt\@4.1.0/node_modules/chatgpt/build/index.js
**此处 chatgpt\@4.1.0 路径不是绝对的!请根据自己安装的版本进行替换!**
**将 // src/fetch.ts 部分修改成如下样子,其他部分不要动**
```
// src/fetch.ts
import fetch from 'node-fetch';
globalThis.fetch = fetch;
```
再编辑`Yunzai根目录/plugins/chatgpt-plugin/config/config.js`文件,根据其中的注释修改必要配置项。
---

398
README.md
View file

@ -1,294 +1,155 @@
# 云崽qq机器人的chatgpt插件
![chatgpt-plugin](https://socialify.git.ci/ikechan8370/chatgpt-plugin/image?description=1&font=Jost&forks=1&issues=1&language=1&name=1&owner=1&pulls=1&stargazers=1&theme=Light)
<div align=center>
![GitHub issues](https://img.shields.io/github/issues/ikechan8370/chatgpt-plugin?logo=github)
![GitHub](https://img.shields.io/github/license/ikechan8370/chatgpt-plugin)
![GitHub tag (latest by date)](https://img.shields.io/github/v/tag/ikechan8370/chatgpt-plugin?label=latest%20version&logo=github)
![GitHub top language](https://img.shields.io/github/languages/top/ikechan8370/chatgpt-plugin?logo=github)
<img src ="https://img.shields.io/github/issues/ikechan8370/chatgpt-plugin?logo=github"/>
<img src ="https://img.shields.io/github/license/ikechan8370/chatgpt-plugin"/>
<img src ="https://img.shields.io/github/v/tag/ikechan8370/chatgpt-plugin?label=latest%20version&logo=github"/>
<img src ="https://img.shields.io/github/languages/top/ikechan8370/chatgpt-plugin?logo=github"/>
</div>
## 特点
* 支持单人连续对话Conversation群聊中支持加入其他人的对话
* API模式下使用 gpt-3.5-turbo APIChatGPT官网同款模型仅需OpenAI Api Key开箱即用。**注意收费**
* 支持问答图片截图
* 支持AI性格调教
* 支持对接vits回答直接转语音
* API3模式下绕过Cloudflare防护直接访问ChatGPT的SSE API与官方体验一致且保留对话记录在官网可查。免费。
* (Deprecated)提供基于浏览器的解决方案作为备选API3不可用的情况下或担心账户安全的用户可以选择使用浏览器模式。
* 支持新[必应](https://www.bing.com/new)Beta
* 2023-03-15 API3支持GPT-4尝鲜需要Plus用户
* 支持[ChatGLM](https://github.com/THUDM/ChatGLM-6B)模型。基于[自建API](https://github.com/ikechan8370/SimpleChatGLM6BAPI)
### 如果觉得这个插件有趣或者对你有帮助请点一个star吧
![26224FE397F1E74104C1C007C1A32DDE](https://user-images.githubusercontent.com/21212372/227718994-4d33da74-6886-41d5-afd0-73986b086df0.gif)
## 版本要求
Node.js >= 18 / Node.js >= 14(with node-fetch)
小白尽可能使用18版本以上的nodejs
## 安装与使用方法
### 安装
在安装之前请先判断自己需要使用哪种模式本插件支持官方API/第三方API/浏览器/必应四种模式。也可以选择**我全都要**(通过qq发送命令`#chatgpt切换浏览器/API/API3/Bing`实时切换)
> 插件v3大幅重构中基本可用持续完善中。遇到问题请提issue欢迎PR。
> todo列表
> - [x] 插件v3重构完成插件基本功能可用持续完善中。
> - [ ] RAG知识库
> - [ ] 预设更详细的配置
> - [x] 自定义触发器
> - [ ] 自定义插件
> - [ ] 兼容mcp
对于轻量用户可以先使用API模式有较高要求再转为使用其他模式。
> #### API模式和浏览器模式如何选择
>
> * API模式会调用OpenAI官方提供的gpt-3.5-turbo APIChatGPT官网同款模型只需要提供API Key。一般情况下该种方式响应速度更快可配置项多且不会像chatGPT官网一样总出现不可用的现象但注意API调用是收费的新用户有18美元试用金可用于支付价格为`$0.0020/1K tokens`。(问题和回答**加起来**算token
> * API3模式会调用第三方提供的官网反代API他会帮你绕过CF防护需要提供ChatGPT的Token。效果与官网和浏览器一致但稳定性不一定。发送#chatgpt设置token来设置token
> * (Deprecated)浏览器模式通过在本地启动Chrome等浏览器模拟用户访问ChatGPT网站使得获得和官方以及API2模式一模一样的回复质量同时保证安全性。缺点是本方法对环境要求较高需要提供桌面环境和一个可用的代理能够访问ChatGPT的IP地址且响应速度不如API而且高峰期容易无法使用。一般作为API3的下位替代。
> * 必应Bing将调用微软新必应接口进行对话。需要在必应网页能够正常使用新必应且设置有效的Bing登录Cookie方可使用。
1. 进入 Yunzai根目录
## 插件简介
2. 请将 chatgpt-plugin 放置在 Yunzai-Bot 的 plugins 目录下
ChatGPT-Plugin 以 Chaite 为内核将多模型渠道、工具、处理器、触发器、RAG 和管控面板封装成一套适配 Miao-Yunzai / Yunzai-Bot 的插件方案。通过 Chaite 的 API 服务器与可插拔的存储层(默认 SQLite插件可以在本地完成高并发对话、知识库检索、伪人陪聊以及记忆管理亦可接入 Chaite Cloud 复用在线渠道与工具。
推荐使用 git 进行安装,以方便后续升级。在 Yunzai-Bot 根目录夹打开终端,运行下述指令进行安装
## 核心特性
```shell
git clone --depth=1 https://github.com/ikechan8370/chatgpt-plugin.git ./plugins/chatgpt-plugin/
cd plugins/chatgpt-plugin
pnpm i
- **多渠道与预设体系**:依托 Chaite 的 ChannelsManager 与 ChatPresetManager支持为不同模型配置流量、负载均衡与个性化 prompt群友也可在授权后自助切换预设。
- **高级消息适配**:前后文触发方式支持 `@Bot` 与前缀;自动处理引用、图片、语音等多模态输入,并在工具调用或推理阶段通过转发消息回显。
- **群上下文与伪人模式**可按配置注入指定条数的群聊记录BYM 伪人模式支持概率触发、关键词命中、预设覆盖及限时撤回,营造更拟人的陪聊体验。
- **记忆与 RAG**:内置 memoryService + vectra 向量索引提供群记忆、私人记忆与外部知识库RAGManager注入能力支持混合检索与手动管理。
- **可视化与指令双管控**`#chatgpt管理面板` 一键获取面板 tokenWeb 端即可操作渠道、工具、触发器;同时保留完整的命令行 CRUD 指令。
- **自动更新与依赖管理**`#chatgpt更新` / `#chatgpt强制更新` 调用 git 同步仓库并自动更新 chaite 依赖,减少手动维护成本。
## 快速安装
1. **克隆代码**
```bash
cd plugins
git clone https://github.com/ikechan8370/chatgpt-plugin.git
```
2. **安装依赖**(推荐 Node.js ≥ 18 + pnpm ≥ 8
```bash
cd chatgpt-plugin
pnpm install
```
若安装日志出现 `Ignored build scripts: better-sqlite3` 或运行时报错找不到 `better-sqlite3` bindings可执行 `pnpm approve-builds`,在交互列表中勾选全部或仅 `better-sqlite3` 以允许编译。然后再次 `pnpm install`
3. **在 Yunzai 中启用插件**
- 重启机器人或运行 `node app` 让插件自动加载。
- 首次启动会在 `plugins/chatgpt-plugin/config/` 下生成 `config.json / config.yaml`
4. **保持更新**
- 主人账号发送 `#chatgpt更新` 获取最新版本。
- `#chatgpt强制更新` 会放弃本地修改后重新拉取,请谨慎使用。
## 配置指引
配置文件默认位于 `plugins/chatgpt-plugin/config/config.json`,也可改写为 YAML。常用字段示例
```yaml
basic:
toggleMode: at # at / prefix
togglePrefix: "#chat" # prefix 模式下的触发词
commandPrefix: "#chatgpt" # 管理指令前缀
llm:
defaultModel: "gpt-4o-mini"
defaultChatPresetId: "default"
enableGroupContext: true
groupContextLength: 20
bym:
enable: false
probability: 0.02
defaultPreset: "bym_default"
chaite:
cloudApiKey: "" # 可选,接入 Chaite Cloud
host: "0.0.0.0"
port: 48370
memory:
group:
enable: false
enabledGroups: ["123456"]
user:
enable: false
whitelist: ["123456789"]
```
如果是手工下载的 zip 压缩包,请将解压后的 chatgpt-plugin 文件夹(请删除压缩自带的-master后缀放置在 Yunzai-Bot 目录下的 plugins 文件夹内
- **basic**:控制触发方式、调试与命令前缀。
- **llm**:定义默认模型、嵌入模型、群上下文等。`defaultChatPresetId` 需在面板或命令中提前创建。
- **chaite**`storage` 默认 SQLite会在 `plugins/chatgpt-plugin/data/data.db` 生成数据文件;如接入 Chaite Cloud请填入 `cloudApiKey` 并开放 `host/port`
- **bym**:配置伪人触发概率、关键词映射、撤回与思考内容开关。
- **memory**:为群记忆或私人记忆开启检索、模型与提示词,可按需启用 `extensions.simple` 以加载自定义词典。
> 浏览器模式仅为备选,如您需要使用浏览器模式,您还需要有**桌面环境**优先级建议API≈必应>API3>浏览器
> 2.20更新必应被大削变得蠢了建议还是API/API3优先
修改后保存文件,插件会自动热加载;在 Chaite 面板修改配置时也会反向写回本地文件。
3. 修改配置
**本插件配置项比较多,建议使用[锅巴面板](https://github.com/guoba-yunzai/Guoba-Plugin)修改**
## 使用方式
复制`plugins/chatgpt-plugin/config/config.example.json`并将其改名为`config.json`\
编辑`plugins/chatgpt-plugin/config/config.json`文件,修改必要配置项
### 基础对话
4. 重启Yunzai-Bot
- `@Bot 你好``#chat 今天天气如何` 触发默认预设,插件会保持用户 `conversationId``messageId`,自动续写多轮对话。
- 回复图片/文本可作为上下文输入,模型返回的图片、语音与思考内容会自动转换为 QQ 消息或转发记录。
- `#结束对话` 仅清空自己的会话;`#结束全部对话` 需主人权限。
> ### 我想使用浏览器模式但是我是linux云服务器没有桌面环境怎么办
>
> linux云服务器可以安装窗口管理器和vnc创建并访问虚拟桌面环境
>
> 1. 安装xvfb和fluxbox
>
> - Ubuntu`sudo apt-get install x11vnc xvfb fluxbox`
>
> - CentOS`sudo yum install x11vnc Xvfb fluxbox`
>
> 2. 启动桌面环境
>
> 建议用tmux或screen等使其能够后台运行
>
> 注意本命令使用默认5900端口和**无密码**,注意通过防火墙等保护,**切勿**在公网环境或不安全的网络环境下使用!!!
> `x11vnc -create -env FD_PROG=/usr/bin/fluxbox -env X11VNC_FINDDISPLAY_ALWAYS_FAILS=1 -env X11VNC_CREATE_GEOM=${1:-1024x768x16} -nopw -forever`
>
> 3. 使用vnc客户端连接至云桌面
>
> 右键Applications > Shells > Bash打开终端然后进入Yunzai目录下运行node app即可。
>
> 4. 执行pnpm i时sharp安装失败
>
> sharp不影响chatgpt聊天仅影响Dalle2绘图功能。ubuntu可以执行`apt install libvips-dev`之后再`pnpm i`
>
> 实测该方案资源占用低运行稳定基本1核2G的轻量云服务器就足够了。
### 管理命令 & 面板
---
- `#chatgpt管理面板`:生成一次性 token访问 `http://<host>:<port>` 即可使用 Chaite Web 面板。
- CRUD 命令示例(均支持 `列表 / 添加 / 查看 / 删除`
```
#chatgpt渠道列表
#chatgpt预设添加 角色扮演 {...}
#chatgpt工具删除 web-search
#chatgpt处理器查看 markdown
```
- `#chatgpt调试模式开关``#chatgpt伪人开关` 等指令可快速切换全局开关。
### 伪人BYM模式
1. 在配置中启用 `bym.enable` 并指定 `defaultPreset``presetMap`
2. 伪人会在命中关键词或达到概率阈值时主动发言,可通过 `presetPrefix` 调整统一人设,`temperature/maxTokens` 控制语气与长度。
3. 支持为不同关键词配置 `recall` 秒数,实现“发完撤回”效果。
### 记忆系统
- **群记忆指令**
```
#群记忆 #仅群聊
#删除群记忆 1 #主人或群管
#记忆列表 #主人查看全局开关
```
- **私人记忆指令**
```
#记忆 / 我的记忆
#他的记忆 @xxx #群聊内查看他人(需其授权)
#删除记忆 1
```
- 记忆抽取依赖配置中的 `memory.group` / `memory.user` 模型与预设collector 会定期读取群聊历史,必要时可在 `enabledGroups` 中按群号白名单控制。
### 更新与维护
- `#chatgpt更新`git pull 插件仓库并使用 pnpm/npm 更新 chaite 依赖。
- `#chatgpt强制更新`:在更新前执行 `git checkout .`,用于舍弃本地改动。
- 日志会通过转发消息发送最近 20 条 commit方便追踪版本变化。
## 赞助
### 相关配置
如果觉得本项目好玩或者对你有帮助,愿意的话可以赞助我一口快乐水:
#### 配置文件相关
配置文件位置:`plugins/chatgpt-plugin/config/config.js`
部分关键配置项,其他请参照文件内注释:
| 名称 | 含义 | 解释 |
| :---------------: | :-----------------: | :----------------------------------------------------: |
| PROXY | 代理地址 | 请在此处配置你的代理,例如`http://127.0.0.1:7890` |
| API_KEY | openai账号的API Key | 获取地址https://platform.openai.com/account/api-keys |
| username/password | openai的账号和密码 | / |
#### Token相关
与Token相关的设置需在qq与机器人对话设置设置后方可使用对应的api
| 名称 | 含义 | 解释 | 设置方式 |
| :-----------------: | :------------------: | :----------------------------------------------------------: | :--------------------: |
| ChatGPT AccessToken | ChatGPT登录后的Token | 具体解释见下方 | \#chatgpt设置token |
| 必应token | 必应登录后的Token | 必应Bing将调用微软新必应接口进行对话。需要在必应网页能够正常使用新必应且设置有效的Bing 登录Cookie方可使用 | \#chatgpt设置必应token |
> #### 我没有注册openai账号如何获取
>
> 您可以按照以下方法获取openai账号
>
> 进入https://chat.openai.com/ 选择signup注册。目前openai不对包括俄罗斯、乌克兰、伊朗、中国等国家和地区提供服务所以自行寻找办法使用**其他国家和地区**的ip登录。此外注册可能需要验证所在国家和地区的手机号码如果没有国外手机号可以试试解码网站收费的推荐https://sms-activate.org/
>
> #### 我有openai账号了如何获取API key和Access Token
>
> - 获取API key
> - 进入账户后台创建API keyCreate new secret keyhttps://platform.openai.com/account/api-keys
>
> - 获取Access Token
> - **登录后**访问https://chat.openai.com/api/auth/session
> - 您会获得类似如下一串json字符串`{"user":{"id":"AAA","name":"BBB","email":"CCC","image":"DDD","picture":"EEE","groups":[]},"expires":"FFF","accessToken":"XXX"}`
> - 其中的XXX即为`ChatGPT AccessToken`
>
> #### ChatGPT AccessToken 设置了有什么用我为什么用不了API模式
>
> - 请参考上方 [API模式和浏览器模式如何选择](#API模式和浏览器模式如何选择)
> - 部分API需要在和机器人的聊天里输入`#chatgpt设置token`才可以使用
>
> #### 我有新必应的测试资格了如何获取必应Token
>
> 1. JS一键获取
>
> 登录www.bing.com刷新一下网页按F12或直接打开开发者模式点击Console/控制台运行如下代码执行后即在您的剪切板存储了必应Token
>
> ```js
> copy(document.cookie.split(";").find(cookie=>cookie.trim().startsWith("_U=")).split("=")[1]);
> ```
>
> 2. 手动获取
>
> 登录www.bing.com刷新一下网页按F12或直接打开开发者模式点击Application/存储点击左侧Storage下的Cookies展开找到[https://www.bing.com](https://www.bing.com/) 项在右侧列表Name项下找到"\_U"_U的value即为必应Token
>
>
>
> 其他问题可以参考使用的api库 https://github.com/transitive-bullshit/chatgpt-api 以及 https://github.com/waylaidwanderer/node-chatgpt-api
### 使用方法
根据配置文件中的toggleMode决定联通方式。
- at模式@机器人 发送聊内容即可
- prefix模式#chat+问题】,本模式可以避免指令冲突。
发挥你的想象力吧,~~调教~~拟造出你自己的机器人风格!
#### 文本/图片回复模式
> #chatgpt文本/图片/语音模式
可以控制机器人回复的方式
#### 对话相关
> #chatgpt对话列表
>
> #结束对话 [@某人]
>
> #清空chat队列
>
> #移出chat队列首位
>
> #chatgpt开启/关闭问题确认
>
> ...
#### 设置相关
> #chat切换浏览器/API/API2/API3/Bing
>
> #chatgpt设置[必应]Token
>
> ...
#### 获取帮助
> #chatgpt帮助
>
> #chatgpt模式帮助
发送#chatgpt帮助,有更多选项可以配置
### 如何更新
发送#chatgpt更新指令。如果有冲突,可以使用#chatgpt强制更新
## 示例与截图
- 程序员版
![img.png](resources/img/example1.png)
- 傲娇版
![)T@~XY~NWXUM S1)D$7%I3H](https://user-images.githubusercontent.com/21212372/217540723-0b97553a-f4ba-41df-ae0c-0449f73657fc.png)
![image](https://user-images.githubusercontent.com/21212372/217545618-3793d9f8-7941-476b-81f8-4255ac216cf7.png)
## TODO
* prompt预设与共享
## 其他
### 常见问题
1. 如果在linux系统上发现图片模式下emoj无法正常显示可以搜索安装支持emoj的字体如Ubuntu可以使用`sudo apt install fonts-noto-color-emoji`
2. 我和机器人聊天但没有任何反应怎么办?
可能是由于Yunzai-bot异常退出等原因造成Redis 队列中有残留的等待问题。使用`#清空队列`命令清除队列后再试。
3. Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'xxx'.
请参照本文档前面的安装依赖部分重新依赖。随着项目更新可能引入新的依赖。
> 一般情况下请按照 [安装](#安装) 小节的内容重新安装依赖即可
>
>
>
> 最多的问题载入插件错误chat
>
> 问题详情Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'showdown' imported from /app/Yunzai-Bot/plugins/chatgpt-plugin/apps/chat.js
>
> 原因:没装依赖
>
> 解决方式:请参考文档在本插件目录下用`pnpm install`安装依赖,安装完就不报错了
4. 反代能自己搭吗?
能。参考[这里](https://ikechan8370.com/archives/da-jian-chatgpt-guan-fang-fan-xiang-dai-li)
5. vit API能本地搭建吗
能。克隆下来安装依赖直接运行即可。
## 交流群
* QQ 559567232
## 感谢
本项目使用或参考了以下开源项目
* https://github.com/transitive-bullshit/chatgpt-api
* https://github.com/waylaidwanderer/node-chatgpt-api
* https://github.com/acheong08/ChatGPT
* https://github.com/PawanOsman
本插件的辅助项目
* https://github.com/ikechan8370/node-chatgpt-proxy
* https://github.com/ikechan8370/SimpleChatGLM6BAPI
图片以及Bing模式支持 @HalcyonAlcedo
* https://github.com/HalcyonAlcedo/ChatGPT-Plugin-PageCache
语音vits模型来自于
* https://huggingface.co/spaces/sayashi/vits-uma-genshin-honkai
以及ChatGPT及OpenAI
* https://chat.openai.com/
* https://platform.openai.com/
ChatGLM
* https://huggingface.co/THUDM/chatglm-6b
* https://github.com/THUDM/ChatGLM-6B
https://afdian.net/a/ikechan8370
## 贡献者
@ -300,3 +161,8 @@ ChatGLM
![Alt](https://repobeats.axiom.co/api/embed/076d597ede41432208435f233d18cb20052fb90a.svg "Repobeats analytics image")
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=ikechan8370/chatgpt-plugin&type=Date)](https://star-history.com/#ikechan8370/chatgpt-plugin&Date)

View file

@ -1,8 +0,0 @@
## 本插件使用的一些redis键值说明
### 官方API3/浏览器模式)
* CHATGPT:QQ_CONVERSATION:123456789 qq号为123456789的人当前正在使用哪个对话
* CHATGPT:CONVERSATION_LAST_MESSAGE_ID:26001339-9043-435d-8394-c553a3109fdf id为`26001339-9043-435d-8394-c553a3109fdf`的对话最后一条用户发出的消息的id
* CHATGPT:CONVERSATION_LAST_MESSAGE_PROMPT:26001339-9043-435d-8394-c553a3109fdf id为`26001339-9043-435d-8394-c553a3109fdf`的对话,最后一条用户发出的消息的内容(问题)
* CHATGPT:CONVERSATION_CREATE_TIME:26001339-9043-435d-8394-c553a3109fdf id为`26001339-9043-435d-8394-c553a3109fdf`的对话创建时间
* CHATGPT:CONVERSATION_LENGTH:26001339-9043-435d-8394-c553a3109fdf id为`26001339-9043-435d-8394-c553a3109fdf`的对话当前长度(不计分支)

155
apps/bym.js Normal file
View file

@ -0,0 +1,155 @@
import ChatGPTConfig from '../config/config.js'
import { Chaite } from 'chaite'
import { intoUserMessage, toYunzai } from '../utils/message.js'
import common from '../../../lib/common/common.js'
import { getGroupContextPrompt } from '../utils/group.js'
import { formatTimeToBeiJing } from '../utils/common.js'
import { extractTextFromUserMessage, processUserMemory } from '../models/memory/userMemoryManager.js'
import { buildMemoryPrompt } from '../models/memory/prompt.js'
export class bym extends plugin {
constructor () {
super({
name: 'ChatGPT-Plugin伪人模式',
dsc: 'ChatGPT-Plugin伪人模式',
event: 'message',
priority: 6000,
rule: [
{
reg: '^[^#][sS]*',
fnc: 'bym',
log: false
}
]
})
}
async bym (e) {
if (!Chaite.getInstance()) {
return false
}
if (!ChatGPTConfig.bym.enable) {
return false
}
let prob = ChatGPTConfig.bym.probability
if (ChatGPTConfig.bym.hit.find(keyword => e.msg?.includes(keyword))) {
prob = 1
}
if (Math.random() > prob) {
return false
}
logger.info('伪人模式触发')
let recall = false
let presetId = ChatGPTConfig.bym.defaultPreset
if (ChatGPTConfig.bym.presetMap && ChatGPTConfig.bym.presetMap.length > 0) {
const option = ChatGPTConfig.bym.presetMap.sort((a, b) => b.priority - a.priority)
.find(item => item.keywords.find(keyword => e.msg?.includes(keyword)))
if (option) {
presetId = option.presetId
recall = !!option.recall
}
}
const presetManager = Chaite.getInstance().getChatPresetManager()
let preset = await presetManager.getInstance(presetId)
if (!preset) {
preset = await presetManager.getInstance(ChatGPTConfig.bym.defaultPreset)
}
if (!preset) {
logger.debug('未找到预设,请检查配置文件')
return false
}
/**
* @type {import('chaite').SendMessageOption}
*/
const sendMessageOption = JSON.parse(JSON.stringify(preset.sendMessageOption))
if (ChatGPTConfig.bym.presetPrefix) {
if (!sendMessageOption.systemOverride) {
sendMessageOption.systemOverride = ''
}
sendMessageOption.systemOverride = ChatGPTConfig.bym.presetPrefix + sendMessageOption.systemOverride
}
sendMessageOption.systemOverride = `Current Time: ${formatTimeToBeiJing(new Date().getTime())}\n` + sendMessageOption.systemOverride
if (ChatGPTConfig.bym.temperature >= 0) {
sendMessageOption.temperature = ChatGPTConfig.bym.temperature
}
if (ChatGPTConfig.bym.maxTokens > 0) {
sendMessageOption.maxToken = ChatGPTConfig.bym.maxTokens
}
const userMessage = await intoUserMessage(e, {
handleReplyText: true,
handleReplyImage: true,
useRawMessage: true,
handleAtMsg: true,
excludeAtBot: false,
toggleMode: ChatGPTConfig.basic.toggleMode,
togglePrefix: ChatGPTConfig.basic.togglePrefix
})
const userText = extractTextFromUserMessage(userMessage) || e.msg || ''
// 伪人不记录历史
// sendMessageOption.disableHistoryRead = true
// sendMessageOption.disableHistorySave = true
sendMessageOption.conversationId = 'bym' + e.user_id + Date.now()
sendMessageOption.parentMessageId = undefined
// 设置多轮调用回掉
sendMessageOption.onMessageWithToolCall = async content => {
const { msgs, forward } = await toYunzai(e, [content])
if (msgs.length > 0) {
await e.reply(msgs)
}
for (let forwardElement of forward) {
this.reply(forwardElement)
}
}
const systemSegments = []
if (sendMessageOption.systemOverride) {
systemSegments.push(sendMessageOption.systemOverride)
}
if (userText) {
const memoryPrompt = await buildMemoryPrompt({
userId: e.sender.user_id + '',
groupId: e.isGroup ? e.group_id + '' : null,
queryText: userText
})
if (memoryPrompt) {
systemSegments.push(memoryPrompt)
logger.debug(`[Memory] bym memory prompt: ${memoryPrompt}`)
}
}
if (ChatGPTConfig.llm.enableGroupContext && e.isGroup) {
const contextPrompt = await getGroupContextPrompt(e, ChatGPTConfig.llm.groupContextLength)
if (contextPrompt) {
systemSegments.push(contextPrompt)
}
}
if (systemSegments.length > 0) {
sendMessageOption.systemOverride = systemSegments.join('\n\n')
}
// 发送
const response = await Chaite.getInstance().sendMessage(userMessage, e, {
...sendMessageOption,
chatPreset: preset
})
const { msgs, forward } = await toYunzai(e, response.contents)
if (msgs.length > 0) {
// await e.reply(msgs, false, { recallMsg: recall })
for (let msg of msgs) {
await e.reply(msg, false, { recallMsg: recall ? 10 : 0 })
await common.sleep(Math.floor(Math.random() * 2000) + 1000)
}
}
if (ChatGPTConfig.bym.sendReasoning) {
for (let forwardElement of forward) {
await e.reply(forwardElement, false, { recallMsg: recall ? 10 : 0 })
}
}
await processUserMemory({
event: e,
userMessage,
userText,
conversationId: sendMessageOption.conversationId,
assistantContents: response.contents,
assistantMessageId: response.id
})
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,226 +0,0 @@
import plugin from '../../../lib/plugins/plugin.js'
import { segment } from 'oicq'
import { createImage, editImage, imageVariation } from '../utils/dalle.js'
import { makeForwardMsg } from '../utils/common.js'
import _ from 'lodash'
import { Config } from '../utils/config.js'
export class dalle extends plugin {
constructor (e) {
super({
name: 'ChatGPT-Plugin Dalle 绘图',
dsc: 'ChatGPT-Plugin基于OpenAI Dalle的绘图插件',
event: 'message',
priority: 500,
rule: [
{
reg: '^#(chatgpt|ChatGPT|dalle|Dalle)(绘图|画图)',
fnc: 'draw'
},
{
reg: '^#(chatgpt|ChatGPT|dalle|Dalle)(修图|图片变形|改图)$',
fnc: 'variation'
},
{
reg: '^#(搞|改)(她|他)头像',
fnc: 'avatarVariation'
},
{
reg: '^#(chatgpt|dalle)编辑图片',
fnc: 'edit'
}
]
})
}
async draw (e) {
if (!Config.enableDraw) {
this.reply('画图功能未开启')
return false
}
let ttl = await redis.ttl(`CHATGPT:DRAW:${e.sender.user_id}`)
if (ttl > 0 && !e.isMaster) {
this.reply(`冷却中,请${ttl}秒后再试`)
return false
}
let splits = _.split(e.msg, '图', 2)
if (splits.length < 2) {
this.reply('请带上绘图要求')
return false
}
let rules = _.split(splits[1], '/')
let [prompt = '', num = '1', size = '512x512'] = rules.slice(0, 3)
if (['256x256', '512x512', '1024x1024'].indexOf(size) === -1) {
this.reply('大小不符合要求必须是256x256/512x512/1024x1024中的一个')
return false
}
await redis.set(`CHATGPT:DRAW:${e.sender.user_id}`, 'c', { EX: 30 })
let priceMap = {
'1024x1024': 0.02,
'512x512': 0.018,
'256x256': 0.016
}
num = parseInt(num, 10)
if (num > 5) {
this.reply('太多啦!你要花光我的余额吗!')
return false
}
await this.reply(`正在为您绘制大小为${size}${num}张图片,预计消耗${priceMap[size] * num}美元余额,请稍候……`)
try {
let images = (await createImage(prompt, num, size)).map(image => segment.image(`base64://${image}`))
if (images.length > 1) {
this.reply(await makeForwardMsg(e, images, prompt))
} else {
this.reply(images[0], true)
}
} catch (err) {
logger.error(err.response?.data?.error?.message)
this.reply(`绘图失败: ${err.response?.data?.error?.message}`, true)
await redis.del(`CHATGPT:DRAW:${e.sender.user_id}`)
}
}
async variation (e) {
if (!Config.enableDraw) {
this.reply('画图功能未开启')
return false
}
let ttl = await redis.ttl(`CHATGPT:VARIATION:${e.sender.user_id}`)
if (ttl > 0 && !e.isMaster) {
this.reply(`冷却中,请${ttl}秒后再试`)
return false
}
let imgUrl
if (e.source) {
let reply
if (e.isGroup) {
reply = (await e.group.getChatHistory(e.source.seq, 1)).pop()?.message
} else {
reply = (await e.friend.getChatHistory(e.source.time, 1)).pop()?.message
}
if (reply) {
for (let val of reply) {
if (val.type === 'image') {
console.log(val)
imgUrl = val.url
break
}
}
}
} else if (e.img) {
console.log(e.img)
imgUrl = e.img[0]
}
if (!imgUrl) {
this.reply('图呢?')
return false
}
await redis.set(`CHATGPT:VARIATION:${e.sender.user_id}`, 'c', { EX: 30 })
await this.reply('正在为您生成图片变形,请稍候……')
try {
let images = (await imageVariation(imgUrl)).map(image => segment.image(`base64://${image}`))
if (images.length > 1) {
this.reply(await makeForwardMsg(e, images))
} else {
this.reply(images[0], true)
}
} catch (err) {
console.log(err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {}))
this.reply(`绘图失败: ${err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {})}`, true)
await redis.del(`CHATGPT:VARIATION:${e.sender.user_id}`)
}
}
async avatarVariation (e) {
if (!Config.enableDraw) {
this.reply('画图功能未开启')
return false
}
let ats = e.message.filter(m => m.type === 'at').filter(at => at.qq !== e.self_id)
if (ats.length > 0) {
for (let i = 0; i < ats.length; i++) {
let qq = ats[i].qq
let imgUrl = `https://q1.qlogo.cn/g?b=qq&s=0&nk=${qq}`
try {
let images = (await imageVariation(imgUrl)).map(image => segment.image(`base64://${image}`))
if (images.length > 1) {
this.reply(await makeForwardMsg(e, images))
} else {
this.reply(images[0], true)
}
} catch (err) {
console.log(err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {}))
this.reply(`搞失败了: ${err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {})}`, true)
await redis.del(`CHATGPT:VARIATION:${e.sender.user_id}`)
}
}
}
}
async edit (e) {
if (!Config.enableDraw) {
this.reply('画图功能未开启')
return false
}
let ttl = await redis.ttl(`CHATGPT:EDIT:${e.sender.user_id}`)
if (ttl > 0 && !e.isMaster) {
this.reply(`冷却中,请${ttl}秒后再试`)
return false
}
let imgUrl
if (e.source) {
let reply
if (e.isGroup) {
reply = (await e.group.getChatHistory(e.source.seq, 1)).pop()?.message
} else {
reply = (await e.friend.getChatHistory(e.source.time, 1)).pop()?.message
}
if (reply) {
for (let val of reply) {
if (val.type === 'image') {
console.log(val)
imgUrl = val.url
break
}
}
}
} else if (e.img) {
console.log(e.img)
imgUrl = e.img[0]
}
if (!imgUrl) {
this.reply('图呢?')
return false
}
await redis.set(`CHATGPT:EDIT:${e.sender.user_id}`, 'c', { EX: 30 })
await this.reply('正在为您编辑图片,请稍候……')
let command = _.trimStart(e.msg, '#chatgpt编辑图片')
command = _.trimStart(command, '#dalle编辑图片')
// command = 'A bird on it/100,100,300,200/2/512x512'
let args = command.split('/')
let [prompt = '', position = '', num = '1', size = '512x512'] = args.slice(0, 4)
if (!prompt || !position) {
this.reply('编辑图片必须填写prompt和涂抹位置.参考格式A bird on it/100,100,300,200/2/512x512')
return false
}
num = parseInt(num, 10)
if (num > 5) {
this.reply('太多啦!你要花光我的余额吗!')
return false
}
try {
let images = (await editImage(imgUrl, position.split(',').map(p => parseInt(p, 10)), prompt, num, size))
.map(image => segment.image(`base64://${image}`))
if (images.length > 1) {
this.reply(await makeForwardMsg(e, images, prompt))
} else {
this.reply(images[0], true)
}
} catch (err) {
logger.error(err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {}))
this.reply(`图片编辑失败: ${err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {})}`, true)
await redis.del(`CHATGPT:EDIT:${e.sender.user_id}`)
}
}
}

View file

@ -1,84 +0,0 @@
import plugin from '../../../lib/plugins/plugin.js'
import { Config } from '../utils/config.js'
import { generateHello } from '../utils/randomMessage.js'
import { segment } from 'oicq'
import { generateAudio } from '../utils/tts.js'
export class Entertainment extends plugin {
constructor (e) {
super({
name: 'ChatGPT-Plugin娱乐小功能',
dsc: 'ChatGPT-Plugin娱乐小功能',
event: 'message',
priority: 500,
rule: [
{
reg: '^#(chatgpt|ChatGPT)打招呼',
fnc: 'sendMessage',
permission: 'master'
}
]
})
this.task = [
{
// 每半小时
cron: '*/30 * * * ?',
name: 'ChatGPT主动随机说话',
fnc: this.sendRandomMessage.bind(this)
}
]
}
async sendMessage (e) {
let groupId = e.msg.replace(/^#(chatgpt|ChatGPT)打招呼/, '')
groupId = parseInt(groupId)
if (groupId && !Bot.getGroupList().get(groupId)) {
await e.reply('机器人不在这个群里!')
return
}
let message = await generateHello()
let sendable = message
logger.info(`打招呼给群聊${groupId}` + message)
if (Config.defaultUseTTS) {
let audio = await generateAudio(message, Config.defaultTTSRole)
sendable = segment.record(audio)
}
if (!groupId) {
await e.reply(sendable)
} else {
await Bot.sendGroupMsg(groupId, sendable)
await e.reply('发送成功!')
}
}
async sendRandomMessage () {
if (Config.debug) {
logger.info('开始处理ChatGPT随机打招呼。')
}
let toSend = Config.initiativeChatGroups || []
for (let i = 0; i < toSend.length; i++) {
if (!toSend[i]) {
continue
}
let groupId = parseInt(toSend[i])
if (Bot.getGroupList().get(groupId)) {
// 5%的概率打招呼
if (Math.floor(Math.random() * 100) < 5 && !(await redis.get(`CHATGPT:HELLO_GROUP:${groupId}`))) {
await redis.set(`CHATGPT:HELLO_GROUP:${groupId}`, '1', { EX: 3600 * 6 })
let message = await generateHello()
logger.info(`打招呼给群聊${groupId}` + message)
if (Config.defaultUseTTS) {
let audio = await generateAudio(message, Config.defaultTTSRole)
await Bot.sendGroupMsg(groupId, segment.record(audio))
} else {
await Bot.sendGroupMsg(groupId, message)
}
} else {
logger.info(`时机未到,这次就不打招呼给群聊${groupId}`)
}
} else {
logger.warn('机器人不在要发送的群组里,忽略群。同时建议检查配置文件修改要打招呼的群号。' + groupId)
}
}
}
}

View file

@ -1,262 +0,0 @@
import plugin from '../../../lib/plugins/plugin.js'
import { Config } from '../utils/config.js'
import { render } from '../utils/common.js'
let version = Config.version
let helpData = [
{
group: '聊天',
list: [
{
icon: 'chat',
title: Config.toggleMode === 'at' ? '@我+聊天内容' : '#chat+聊天内容',
desc: '与机器人聊天'
},
{
icon: 'chat',
title: '#chat1/#chat3/#chatglm/#bing',
desc: '分别使用API/API3/ChatGLM/Bing模式与机器人聊天无论主人设定了何种全局模式'
},
{
icon: 'chat-private',
title: '私聊与我对话',
desc: '与机器人聊天'
},
{
icon: 'switch',
title: '#chatgpt切换对话+对话id',
desc: '目前仅API3模式下可用切换到指定的对话中'
},
{
icon: 'switch',
title: '#chatgpt加入对话+@某人',
desc: '目前仅API3模式下可用加入到某人当前进行的对话中'
},
{
icon: 'destroy',
title: '#chatgpt删除对话+对话id或@用户',
desc: '删除指定对话,并清空与用户的关联信息。@用户时支持多个用户'
},
{
icon: 'destroy',
title: '#结束对话',
desc: '结束自己当前对话,下次开启对话机器人将遗忘掉本次对话内容。'
},
{
icon: 'destroy',
title: '#结束全部对话',
desc: '结束正在与本机器人进行对话的全部用户的对话。'
},
{
icon: 'destroy-other',
title: '#结束对话 @某人',
desc: '结束该用户当前对话,下次开启对话机器人将遗忘掉本次对话内容。'
}
]
},
{
group: '画图',
list: [
{
icon: 'draw',
title: '#chatgpt画图+prompt(/张数/图片大小)',
desc: '调用OpenAI Dalle API进行绘图需要有API key并消耗余额。图片大小只能是256x256/512x512/1024x1024中的一个.默认为1张、512x512'
},
{
icon: 'draw',
title: '#chatgpt改图',
desc: '调用OpenAI Dalle API进行改图需要有API key并消耗余额。可同时发送图片或回复图片'
},
{
icon: 'switch',
title: '#chatgpt开启/关闭画图',
desc: '开启或关闭画图功能'
}
]
},
{
group: '管理',
list: [
{
icon: 'picture',
title: '#chatgpt图片模式',
desc: '机器人以图片形式回答'
},
{
icon: 'text',
title: '#chatgpt文本模式',
desc: '机器人以文本形式回答,默认选项'
},
{
icon: 'sound',
title: '#chatgpt语音模式',
desc: '机器人以语音形式回答'
},
{
icon: 'game',
title: '#chatgpt设置语音角色',
desc: '设置语音模式下回复的角色音色'
},
{
icon: 'list',
title: '#chatgpt对话列表',
desc: '查询当前哪些人正在与机器人聊天.目前API3模式下支持切换对话'
},
{
icon: 'blue',
title: '#chatgpt(本群)?(群xxx)?闭嘴(x秒/分钟/小时)',
desc: '让机器人在本群/某群闭嘴。不指定群时认为全局闭嘴。'
},
{
icon: 'eye',
title: '#chatgpt(本群)?(群xxx)?(张嘴|开口|说话|上班)',
desc: '让机器人在本群/某群重新可以说话。不指定群时认为全局开口。'
},
{
icon: 'list',
title: '#chatgpt查看闭嘴',
desc: '查看当前闭嘴情况。'
},
{
icon: 'queue',
title: '#清空chat队列',
desc: '清空当前对话等待队列。仅建议前方卡死时使用。仅API3模式下可用'
},
{
icon: 'queue',
title: '#移出chat队列首位',
desc: '移出当前对话等待队列中的首位。若前方对话卡死可使用本命令。仅API3模式下可用'
},
{
icon: 'confirm',
title: '#chatgpt开启/关闭问题确认',
desc: '开启或关闭机器人收到消息后的确认回复消息。'
},
{
icon: 'switch',
title: '#chatgpt切换浏览器/API/API3/Bing/ChatGLM',
desc: '切换使用的后端为浏览器或OpenAI API/反代官网API/Bing/自建ChatGLM'
},
{
icon: 'confirm',
title: '#chatgpt必应切换(精准|均衡|创意|悉尼|自设定)',
desc: '切换Bing风格。'
},
{
icon: 'confirm',
title: '#chatgpt必应(开启|关闭)建议回复',
desc: '开关Bing模式下的建议回复。'
}
]
},
{
group: '设置',
list: [
{
icon: 'token',
title: '#chatgpt设置必应token',
desc: '设置ChatGPT或bing的Token'
},
{
icon: 'coin',
title: '#OpenAI剩余额度',
desc: '查询OpenAI API剩余试用额度'
},
{
icon: 'key',
title: '#chatgpt设置APIKey',
desc: '设置APIKey'
},
{
icon: 'eat',
title: '#chatgpt设置(API|Sydney)设定',
desc: '设置AI的默认风格设定'
},
{
icon: 'eat',
title: '#chatgpt查看(API|Sydney)设定',
desc: '查看AI当前的风格设定文本形式返回设定太长可能发不出来'
}
]
},
{
group: '设定',
list: [
{
icon: 'smiley-wink',
title: '#chatgpt设定列表',
desc: '查看所有设定列表,以转发消息形式'
},
{
icon: 'eat',
title: '#chatgpt查看设定【设定名】',
desc: '查看指定名字的设定内容。其中API默认和Sydney默认为锅巴面板配置的设定'
},
{
icon: 'coin',
title: '#chatgpt添加设定',
desc: '添加一个设定,分此输入设定名称和设定内容'
},
{
icon: 'switch',
title: '#chatgpt使用设定【设定名】',
desc: '使用某个设定'
},
{
icon: 'confirm',
title: '#chatgpt(上传|分享|共享)设定',
desc: '敬请期待'
},
{
icon: 'confirm',
title: '#chatgpt导入设定',
desc: '敬请期待'
},
{
icon: 'help',
title: '#chatgpt设定帮助',
desc: '设定帮助'
},
]
},
{
group: '其他',
list: [
{
icon: 'smiley-wink',
title: '#chatgpt打招呼(群号)',
desc: '让AI随机到某个群去打招呼'
},
{
icon: 'help',
title: '#chatgpt模式帮助',
desc: '查看多种聊天模式的区别及当前使用的模式'
},
{
icon: 'help',
title: '#chatgpt帮助',
desc: '获取本帮助'
}
]
}
]
export class help extends plugin {
constructor (e) {
super({
name: 'ChatGPT-Plugin帮助',
dsc: 'ChatGPT-Plugin帮助',
event: 'message',
priority: 500,
rule: [
{
reg: '^#(chatgpt|ChatGPT)(命令|帮助|菜单|help|说明|功能|指令|使用说明)$',
fnc: 'help'
}
]
})
}
async help (e) {
await render(e, 'chatgpt-plugin', 'help/index', { helpData, version })
}
}

View file

@ -1,575 +1,172 @@
import plugin from '../../../lib/plugins/plugin.js'
import { Config } from '../utils/config.js'
import { BingAIClient } from '@waylaidwanderer/chatgpt-api'
import { exec } from 'child_process'
import { checkPnpm, formatDuration, parseDuration } from '../utils/common.js'
import ChatGPTConfig from '../config/config.js'
import { createCRUDCommandRules, createSwitchCommandRules } from '../utils/command.js'
import { Chaite, VERSION } from 'chaite'
import * as crypto from 'node:crypto'
import common from '../../../lib/common/common.js'
export class ChatgptManagement extends plugin {
constructor (e) {
export class ChatGPTManagement extends plugin {
constructor () {
const cmdPrefix = ChatGPTConfig.basic.commandPrefix
super({
name: 'ChatGPT-Plugin管理',
dsc: 'ChatGPT-Plugin管理',
event: 'message',
priority: 500,
priority: 20,
rule: [
{
reg: '#chatgpt开启(问题)?(回复)?确认',
fnc: 'turnOnConfirm',
reg: `^${cmdPrefix}管理面板$`,
fnc: 'managementPanel',
permission: 'master'
},
{
reg: '#chatgpt关闭(问题)?(回复)?确认',
fnc: 'turnOffConfirm',
reg: `^(${cmdPrefix})?#?结束(全部)?对话$`,
fnc: 'destroyConversation'
},
{
reg: `^${cmdPrefix}(bym|伪人)设置默认预设`,
fnc: 'setDefaultBymPreset',
permission: 'master'
},
{
reg: '#chatgpt(设置|绑定)(token|Token)',
fnc: 'setAccessToken',
permission: 'master'
},
{
reg: '#chatgpt(设置|绑定)(必应|Bing |bing )(token|Token)',
fnc: 'setBingAccessToken',
permission: 'master'
},
{
reg: '^#chatgpt切换浏览器$',
fnc: 'useBrowserBasedSolution',
permission: 'master'
},
{
reg: '^#chatgpt切换API$',
fnc: 'useOpenAIAPIBasedSolution',
permission: 'master'
},
{
reg: '^#chatgpt切换(ChatGLM|chatglm)$',
fnc: 'useChatGLMSolution',
permission: 'master'
},
{
reg: '^#chatgpt切换API3$',
fnc: 'useReversedAPIBasedSolution2',
permission: 'master'
},
{
reg: '^#chatgpt切换(必应|Bing)$',
fnc: 'useBingSolution',
permission: 'master'
},
{
reg: '^#chatgpt(必应|Bing)切换',
fnc: 'changeBingTone',
permission: 'master'
},
{
reg: '^#chatgpt(必应|Bing)(开启|关闭)建议(回复)?',
fnc: 'bingOpenSuggestedResponses',
permission: 'master'
},
{
reg: '^#chatgpt模式(帮助)?$',
fnc: 'modeHelp'
},
{
reg: '^#chatgpt(强制)?更新$',
fnc: 'updateChatGPTPlugin'
},
{
reg: '^#chatgpt(本群)?(群\\d+)?闭嘴',
fnc: 'shutUp',
permission: 'master'
},
{
reg: '^#chatgpt(本群)?(群\\d+)?(张嘴|开口|说话|上班)',
fnc: 'openMouth',
permission: 'master'
},
{
reg: '^#chatgpt查看闭嘴',
fnc: 'listShutUp',
permission: 'master'
},
{
reg: '^#chatgpt设置(API|key)(Key|key)',
fnc: 'setAPIKey',
permission: 'master'
},
{
reg: '^#chatgpt设置(API|api)设定',
fnc: 'setAPIPromptPrefix',
permission: 'master'
},
{
reg: '^#chatgpt设置(Bing|必应|Sydney|悉尼|sydney|bing)设定',
fnc: 'setBingPromptPrefix',
permission: 'master'
},
{
reg: '^#chatgpt(开启|关闭)画图$',
fnc: 'switchDraw',
permission: 'master'
},
{
reg: '^#chatgpt查看(API|api)设定$',
fnc: 'queryAPIPromptPrefix',
permission: 'master'
},
{
reg: '^#chatgpt查看(Bing|必应|Sydney|悉尼|sydney|bing)设定$',
fnc: 'queryBingPromptPrefix',
reg: `^${cmdPrefix}(查看)?(当前)?(配置|信息|统计信息|状态)$`,
fnc: 'currentStatus',
permission: 'master'
}
]
})
}
async turnOnConfirm (e) {
await redis.set('CHATGPT:CONFIRM', 'on')
await this.reply('已开启消息确认', true)
return false
}
async turnOffConfirm (e) {
await redis.set('CHATGPT:CONFIRM', 'off')
await this.reply('已关闭消息确认', true)
return false
}
async setAccessToken (e) {
this.setContext('saveToken')
await this.reply('请发送ChatGPT AccessToken', true)
return false
}
async setBingAccessToken (e) {
this.setContext('saveBingToken')
await this.reply('请发送Bing Cookie Token.("_U" cookie from bing.com)', true)
return false
}
async saveBingToken () {
if (!this.e.msg) return
let token = this.e.msg
if (token.length < 215) {
await this.reply('Bing Token格式错误请确定获取了有效的_U Cookie或完整的Cookie', true)
this.finish('saveToken')
return
}
let cookie
if (token?.indexOf('=') > -1) {
cookie = token
}
const bingAIClient = new BingAIClient({
userToken: token, // "_U" cookie from bing.com
cookie,
debug: Config.debug
})
// 异步就好了不卡着这个context了
bingAIClient.createNewConversation().then(async res => {
if (res.clientId) {
logger.info('bing token 有效')
} else {
logger.error('bing token 无效', res)
await this.reply(`经检测Bing Token无效。来自Bing的错误提示${res.result?.message}`)
}
})
await redis.set('CHATGPT:BING_TOKEN', token)
await this.reply('Bing Token设置成功', true)
this.finish('saveBingToken')
}
async saveToken () {
if (!this.e.msg) return
let token = this.e.msg
if (!token.startsWith('ey') || token.length < 20) {
await this.reply('ChatGPT AccessToken格式错误', true)
this.finish('saveToken')
return
}
await redis.set('CHATGPT:TOKEN', token)
await this.reply('ChatGPT AccessToken设置成功', true)
this.finish('saveToken')
}
async useBrowserBasedSolution (e) {
await redis.set('CHATGPT:USE', 'browser')
await this.reply('已切换到基于浏览器的解决方案,如果已经对话过建议执行`#结束对话`避免引起404错误')
}
async useOpenAIAPIBasedSolution (e) {
let use = await redis.get('CHATGPT:USE')
if (use !== 'api') {
await redis.set('CHATGPT:USE', 'api')
await this.reply('已切换到基于OpenAI API的解决方案如果已经对话过建议执行`#结束对话`避免引起404错误')
} else {
await this.reply('当前已经是API模式了')
}
}
async useChatGLMSolution (e) {
await redis.set('CHATGPT:USE', 'chatglm')
await this.reply('已切换到ChatGLM-6B解决方案如果已经对话过建议执行`#结束对话`避免引起404错误')
}
async useReversedAPIBasedSolution2 (e) {
let use = await redis.get('CHATGPT:USE')
if (use !== 'api3') {
await redis.set('CHATGPT:USE', 'api3')
await this.reply('已切换到基于第三方Reversed Conversastion API(API3)的解决方案')
} else {
await this.reply('当前已经是API3模式了')
}
}
async useBingSolution (e) {
let use = await redis.get('CHATGPT:USE')
if (use !== 'bing') {
await redis.set('CHATGPT:USE', 'bing')
// 结束所有人的对话
const keys = await redis.keys('CHATGPT:CONVERSATIONS:*')
if (keys.length) {
const response = await redis.del(keys)
if (Config.debug) {
console.log('Deleted keys:', response)
if (!Chaite.getInstance()) {
const waitForChaite = async () => {
while (!Chaite.getInstance()) {
await new Promise(resolve => setTimeout(resolve, 1000))
}
} else {
console.log('No keys matched the pattern')
return Chaite.getInstance()
}
await this.reply('已切换到基于微软新必应的解决方案,如果已经对话过务必执行`#结束对话`避免引起404错误')
} else {
await this.reply('当前已经是必应Bing模式了')
}
}
async changeBingTone (e) {
let tongStyle = e.msg.replace(/^#chatgpt(必应|Bing)切换/, '')
if (!tongStyle) {
return
}
let map = {
精准: 'precise',
创意: 'creative',
均衡: 'balanced',
Sydney: 'Sydney',
sydney: 'Sydney',
悉尼: 'Sydney',
自设定: 'Custom',
自定义: 'Custom'
}
if (map[tongStyle]) {
Config.toneStyle = map[tongStyle]
await e.reply('切换成功')
} else {
await e.reply('没有这种风格。支持的风格:精准、创意、均衡、悉尼、自设定')
}
}
async bingOpenSuggestedResponses (e) {
Config.enableSuggestedResponses = e.msg.indexOf('开启') > -1
await e.reply('操作成功')
}
async checkAuth (e) {
if (!e.isMaster) {
e.reply(`只有主人才能命令ChatGPT哦~
(*/ω*)`)
return false
}
return true
}
// modified from miao-plugin
async updateChatGPTPlugin (e) {
let timer
if (!await this.checkAuth(e)) {
return true
}
let isForce = e.msg.includes('强制')
let command = 'git pull'
if (isForce) {
command = 'git checkout . && git pull'
e.reply('正在执行强制更新操作,请稍等')
} else {
e.reply('正在执行更新操作,请稍等')
}
const _path = process.cwd()
exec(command, { cwd: `${_path}/plugins/chatgpt-plugin/` }, async function (error, stdout, stderr) {
if (/(Already up[ -]to[ -]date|已经是最新的)/.test(stdout)) {
e.reply('目前已经是最新版ChatGPT了~')
return true
}
if (error) {
e.reply('ChatGPT更新失败\nError code: ' + error.code + '\n' + error.stack + '\n 请稍后重试。')
return true
}
e.reply('ChatGPT更新成功正在尝试重新启动Yunzai以应用更新...')
e.reply('更新日志:\n' + stdout)
timer && clearTimeout(timer)
let data = JSON.stringify({
isGroup: !!e.isGroup,
id: e.isGroup ? e.group_id : e.user_id,
time: new Date().getTime()
waitForChaite().then(() => {
this.initCommand(cmdPrefix)
})
await redis.set('Yz:restart', data, { EX: 120 })
let npm = await checkPnpm()
timer = setTimeout(function () {
let command = `${npm} start`
if (process.argv[1].includes('pm2')) {
command = `${npm} run restart`
} else {
this.initCommand(cmdPrefix)
}
}
initCommand (cmdPrefix) {
this.rule.push(...[
...createCRUDCommandRules.bind(this)(cmdPrefix, '渠道', 'channels'),
...createCRUDCommandRules.bind(this)(cmdPrefix, '预设', 'presets'),
...createCRUDCommandRules.bind(this)(cmdPrefix, '工具', 'tools'),
...createCRUDCommandRules.bind(this)(cmdPrefix, '处理器', 'processors'),
createSwitchCommandRules.bind(this)(cmdPrefix, '(预设切换|其他人切换预设)', 'customPreset', 1),
createSwitchCommandRules.bind(this)(cmdPrefix, '(调试|debug)(模式)?', 'debug'),
...createCRUDCommandRules.bind(this)(cmdPrefix, '预设切换黑名单', 'customPresetUserBlackList', false),
...createCRUDCommandRules.bind(this)(cmdPrefix, '预设切换白名单', 'customPresetUserWhiteList', false),
...createCRUDCommandRules.bind(this)(cmdPrefix, '输入屏蔽词', 'promptBlockWords', false),
...createCRUDCommandRules.bind(this)(cmdPrefix, '输出屏蔽词', 'responseBlockWords', false),
...createCRUDCommandRules.bind(this)(cmdPrefix, '黑名单群', 'blackGroups', false),
...createCRUDCommandRules.bind(this)(cmdPrefix, '白名单群', 'whiteGroups', false),
...createCRUDCommandRules.bind(this)(cmdPrefix, '黑名单用户', 'blackUsers', false),
...createCRUDCommandRules.bind(this)(cmdPrefix, '白名单用户', 'whiteUsers', false),
createSwitchCommandRules(cmdPrefix, '(伪人|bym)', 'bym')
])
}
managementPanel (e) {
// todo
// this.reply(`(todo)管理面板地址http://${ChatGPTConfig.chaite.host}:${ChatGPTConfig.chaite.host}`)
const token = Chaite.getInstance().getFrontendAuthHandler().generateToken(300)
this.reply(`token: ${token}, 有效期300秒`, true)
}
async setDefaultBymPreset (e) {
const presetId = e.msg.replace(`${ChatGPTConfig.basic.commandPrefix}伪人设置默认预设`, '')
const preset = await Chaite.getInstance().getChatPresetManager().getInstance(presetId)
if (preset) {
ChatGPTConfig.bym.defaultPreset = presetId
this.reply(`伪人模式默认预设已切换为${presetId}(${preset.name})`)
} else {
this.reply(`未找到预设${presetId}`)
}
}
async destroyConversation (e) {
if (e.msg.includes('全部')) {
if (!e.isMaster) {
this.reply('仅限主人使用')
return false
}
const userStates = await Chaite.getInstance().getUserStateStorage().listItems()
// let num = 0
for (const userState of userStates) {
if (userState.current.conversationId && userState.current.messageId) {
// num++
userState.current.conversationId = crypto.randomUUID()
userState.current.messageId = crypto.randomUUID()
await Chaite.getInstance().getUserStateStorage().setItem(userState.userId + '', userState)
}
exec(command, function (error, stdout, stderr) {
if (error) {
e.reply('自动重启失败请手动重启以应用新版ChatGPT。\nError code: ' + error.code + '\n' + error.stack + '\n')
Bot.logger.error(`重启失败\n${error.stack}`)
return true
} else if (stdout) {
Bot.logger.mark('重启成功运行已转为后台查看日志请用命令npm run log')
Bot.logger.mark('停止后台运行命令npm stop')
process.exit()
}
})
}, 1000)
}
this.reply('已结束全部对话')
} else {
const state = await Chaite.getInstance().getUserStateStorage().getItem(e.sender.user_id + '')
if (!state || !state.current.conversationId || !state.current.messageId) {
this.reply('当前未开启对话')
return false
}
state.current.conversationId = crypto.randomUUID()
state.current.messageId = crypto.randomUUID()
await Chaite.getInstance().getUserStateStorage().setItem(e.sender.user_id + '', state)
this.reply('已结束当前对话')
}
}
async currentStatus (e) {
const msgs = []
let basic = `Chaite版本${VERSION}\n`
const user = Chaite.getInstance().getToolsManager().cloudService?.getUser()
if (user) {
basic += `Chaite Cloud已认证 @${user.username}`
} else if (ChatGPTConfig.chaite.cloudBaseUrl) {
basic += 'Chaite Cloud: 未认证'
} else {
basic += 'Chaite Cloud: 未接入'
}
msgs.push(basic)
const allChannels = await Chaite.getInstance().getChannelsManager().getAllChannels()
let channelMsg = `渠道总数:${allChannels.length}\n`
channelMsg += `请使用 ${ChatGPTConfig.basic.commandPrefix}渠道列表 查看全部渠道\n\n`
allChannels.map(c => c.models).reduce((acc, cur) => {
acc.push(...cur)
return acc
}, []).forEach(m => {
channelMsg += `${m}${allChannels.filter(c => c.models.includes(m)).length}\n`
})
return true
}
msgs.push(channelMsg)
async modeHelp () {
let mode = await redis.get('CHATGPT:USE')
const modeMap = {
browser: '浏览器',
// apiReverse: 'API2',
api: 'API',
bing: '必应',
api3: 'API3',
chatglm: 'ChatGLM-6B'
}
let modeText = modeMap[mode || 'api']
let message = ` API模式和浏览器模式如何选择
const allPresets = await Chaite.getInstance().getChatPresetManager().getAllPresets()
let presetMsg = `预设总数:${allPresets.length}\n`
presetMsg += `请使用 ${ChatGPTConfig.basic.commandPrefix}预设列表 查看全部预设`
msgs.push(presetMsg)
// eslint-disable-next-line no-irregular-whitespace
API模式会调用OpenAI官方提供的gpt-3.5-turbo API只需要提供API Key一般情况下该种方式响应速度更快不会像chatGPT官网一样总出现不可用的现象但注意gpt-3.5-turbo的API调用是收费的新用户有18美元试用金可用于支付价格为$0.0020/1K tokens.(问题和回答加起来算token)
API3模式会调用官网反代API他会帮你绕过CF防护需要提供ChatGPT的Token效果与官网和浏览器一致设置token指令#chatgpt设置token
const defaultChatPresetId = ChatGPTConfig.llm.defaultChatPresetId
const currentPreset = await Chaite.getInstance().getChatPresetManager().getInstance(defaultChatPresetId)
msgs.push(`当前预设:${currentPreset?.name || '未设置'}${currentPreset ? ('\n\n' + currentPreset.toFormatedString(false)) : ''}`)
浏览器模式通过在本地启动Chrome等浏览器模拟用户访问ChatGPT网站使得获得和官方以及API2模式一模一样的回复质量同时保证安全性缺点是本方法对环境要求较高需要提供桌面环境和一个可用的代理能够访问ChatGPT的IP地址且响应速度不如API而且高峰期容易无法使用
const allTools = await Chaite.getInstance().getToolsManager().listInstances()
let toolsMsg = `工具总数:${allTools.length}\n`
toolsMsg += `请使用 ${ChatGPTConfig.basic.commandPrefix}工具列表 查看全部工具`
msgs.push(toolsMsg)
必应Bing将调用微软新必应接口进行对话需要在必应网页能够正常使用新必应且设置有效的Bing 登录Cookie方可使用#chatgpt设置必应token
自建ChatGLM模式会调用自建的ChatGLM-6B服务器API进行对话需要自建参考https://github.com/ikechan8370/SimpleChatGLM6BAPI
const allProcessors = await Chaite.getInstance().getProcessorsManager().listInstances()
let processorsMsg = `处理器总数:${allProcessors.length}\n`
processorsMsg += `请使用 ${ChatGPTConfig.basic.commandPrefix}处理器列表 查看全部处理器`
msgs.push(processorsMsg)
您可以使用#chatgpt切换浏览器/API/API3/Bing/ChatGLM来切换到指定模式
const userStatesManager = Chaite.getInstance().getUserStateStorage()
const allUsers = await userStatesManager.listItems()
const currentUserNums = allUsers.filter(u => u.current.conversationId && u.current.messageId).length
const historyUserNums = allUsers.length
msgs.push(`用户总数:${historyUserNums}\n当前对话用户数:${currentUserNums}`)
当前为${modeText}模式
`
await this.reply(message)
}
async shutUp (e) {
let duration = e.msg.replace(/^#chatgpt(本群)?(群\d+)?闭嘴/, '')
let scope
let time = 3600000
if (duration === '永久') {
time = 0
} else if (duration) {
time = parseDuration(duration)
}
const match = e.msg.match(/#chatgpt群(\d+)闭嘴(.*)/)
if (e.msg.indexOf('本群') > -1) {
if (e.isGroup) {
scope = e.group.group_id
if (await redis.get(`CHATGPT:SHUT_UP:${scope}`)) {
await redis.del(`CHATGPT:SHUT_UP:${scope}`)
await redis.set(`CHATGPT:SHUT_UP:${scope}`, '1', { EX: time })
await e.reply(`好的,从现在开始我会在当前群聊闭嘴${formatDuration(time)}`)
} else {
await redis.set(`CHATGPT:SHUT_UP:${scope}`, '1', { EX: time })
await e.reply(`好的,从现在开始我会在当前群聊闭嘴${formatDuration(time)}`)
}
} else {
await e.reply('本群是指?你也没在群聊里让我闭嘴啊?')
return false
}
} else if (match) {
const groupId = parseInt(match[1], 10)
if (Bot.getGroupList().get(groupId)) {
if (await redis.get(`CHATGPT:SHUT_UP:${groupId}`)) {
await redis.del(`CHATGPT:SHUT_UP:${groupId}`)
await redis.set(`CHATGPT:SHUT_UP:${groupId}`, '1', { EX: time })
await e.reply(`好的,从现在开始我会在群聊${groupId}闭嘴${formatDuration(time)}`)
} else {
await redis.set(`CHATGPT:SHUT_UP:${groupId}`, '1', { EX: time })
await e.reply(`好的,从现在开始我会在群聊${groupId}闭嘴${formatDuration(time)}`)
}
} else {
await e.reply('这是什么群?')
return false
}
} else {
if (await redis.get('CHATGPT:SHUT_UP:ALL')) {
await redis.del('CHATGPT:SHUT_UP:ALL')
await redis.set('CHATGPT:SHUT_UP:ALL', '1', { EX: time })
await e.reply(`好的,我会再闭嘴${formatDuration(time)}`)
} else {
await redis.set('CHATGPT:SHUT_UP:ALL', '1', { EX: time })
await e.reply(`好的,我会闭嘴${formatDuration(time)}`)
}
}
}
async openMouth (e) {
const match = e.msg.match(/^#chatgpt群(\d+)/)
if (e.msg.indexOf('本群') > -1) {
if (await redis.get('CHATGPT:SHUT_UP:ALL')) {
await e.reply('主人,我现在全局闭嘴呢,你让我在这个群张嘴咱也不敢张啊')
return false
}
if (e.isGroup) {
let scope = e.group.group_id
if (await redis.get(`CHATGPT:SHUT_UP:${scope}`)) {
await redis.del(`CHATGPT:SHUT_UP:${scope}`)
await e.reply('好的主人,我终于又可以在本群说话了')
} else {
await e.reply('啊?我也没闭嘴啊?')
}
} else {
await e.reply('本群是指?你也没在群聊里让我张嘴啊?')
return false
}
} else if (match) {
if (await redis.get('CHATGPT:SHUT_UP:ALL')) {
await e.reply('主人,我现在全局闭嘴呢,你让我在那个群张嘴咱也不敢张啊')
return false
}
const groupId = parseInt(match[1], 10)
if (Bot.getGroupList().get(groupId)) {
if (await redis.get(`CHATGPT:SHUT_UP:${groupId}`)) {
await redis.del(`CHATGPT:SHUT_UP:${groupId}`)
await e.reply(`好的主人,我终于又可以在群${groupId}说话了`)
} else {
await e.reply(`啊?我也没在群${groupId}闭嘴啊?`)
}
} else {
await e.reply('这是什么群?')
return false
}
} else {
let keys = await redis.keys('CHATGPT:SHUT_UP:*')
if (await redis.get('CHATGPT:SHUT_UP:ALL')) {
await redis.del('CHATGPT:SHUT_UP:ALL')
for (let i = 0; i < keys.length; i++) {
await redis.del(keys[i])
}
await e.reply('好的,我会结束所有闭嘴')
} else if (keys || keys.length > 0) {
for (let i = 0; i < keys.length; i++) {
await redis.del(keys[i])
}
await e.reply('好的,我会结束所有闭嘴?')
} else {
await e.reply('我没有在任何地方闭嘴啊?')
}
}
}
async listShutUp () {
let keys = await redis.keys('CHATGPT:SHUT_UP:*')
if (!keys || keys.length === 0) {
await this.reply('我没有在任何群闭嘴', true)
} else {
let list = []
for (let i = 0; i < keys.length; i++) {
let key = keys[i]
let groupId = key.replace('CHATGPT:SHUT_UP:', '')
let ttl = await redis.ttl(key)
let ttlFormat = formatDuration(ttl)
list.push({ groupId, ttlFormat })
}
await this.reply(list.map(item => item.groupId !== 'ALL' ? `群聊${item.groupId}: ${item.ttlFormat}` : `全局: ${item.ttlFormat}`).join('\n'))
}
}
async setAPIKey (e) {
this.setContext('saveAPIKey')
await this.reply('请发送OpenAI API Key.', true)
return false
}
async saveAPIKey () {
if (!this.e.msg) return
let token = this.e.msg
if (!token.startsWith('sk-')) {
await this.reply('OpenAI API Key格式错误', true)
this.finish('saveAPIKey')
return
}
// todo
Config.apiKey = token
await this.reply('OpenAI API Key设置成功', true)
this.finish('saveAPIKey')
}
async setAPIPromptPrefix (e) {
this.setContext('saveAPIPromptPrefix')
await this.reply('请发送用于API模式的设定', true)
return false
}
async saveAPIPromptPrefix (e) {
if (!this.e.msg) return
if (this.e.msg === '取消') {
await this.reply('已取消设置API设定', true)
this.finish('saveAPIPromptPrefix')
return
}
// todo
Config.promptPrefixOverride = this.e.msg
await this.reply('API模式的设定设置成功', true)
this.finish('saveAPIPromptPrefix')
}
async setBingPromptPrefix (e) {
this.setContext('saveBingPromptPrefix')
await this.reply('请发送用于Bing Sydney模式的设定', true)
return false
}
async saveBingPromptPrefix (e) {
if (!this.e.msg) return
if (this.e.msg === '取消') {
await this.reply('已取消设置Sydney设定', true)
this.finish('saveBingPromptPrefix')
return
}
Config.sydney = this.e.msg
await this.reply('Bing Sydney模式的设定设置成功', true)
this.finish('saveBingPromptPrefix')
}
async switchDraw (e) {
if (e.msg.indexOf('开启') > -1) {
if (Config.enableDraw) {
await this.reply('当前已经开启chatgpt画图功能', true)
} else {
Config.enableDraw = true
await this.reply('chatgpt画图功能开启成功', true)
}
} else {
if (!Config.enableDraw) {
await this.reply('当前未开启chatgpt画图功能', true)
} else {
Config.enableDraw = false
await this.reply('chatgpt画图功能关闭成功', true)
}
}
}
async queryAPIPromptPrefix (e) {
await this.reply(Config.promptPrefixOverride, true)
}
async queryBingPromptPrefix (e) {
await this.reply(Config.sydney, true)
const m = await common.makeForwardMsg(e, msgs, e.msg)
e.reply(m)
}
}

224
apps/memory.js Normal file
View file

@ -0,0 +1,224 @@
import Config from '../config/config.js'
import { GroupMessageCollector } from '../models/memory/collector.js'
import { memoryService } from '../models/memory/service.js'
import common from '../../../lib/common/common.js'
const collector = new GroupMessageCollector()
function isGroupManager (e) {
if (e.isMaster) {
return true
}
if (!e.member) {
return false
}
if (typeof e.member.is_admin !== 'undefined') {
return e.member.is_admin || e.member.is_owner
}
if (typeof e.member.role !== 'undefined') {
return ['admin', 'owner'].includes(e.member.role)
}
return false
}
export class MemoryManager extends plugin {
constructor () {
const cmdPrefix = Config.basic.commandPrefix || '#chatgpt'
super({
name: 'ChatGPT-Plugin记忆系统',
dsc: '处理记忆系统相关的采集与管理',
event: 'message',
priority: 550,
rule: [
// {
// reg: '[\\s\\S]+',
// fnc: 'collect',
// log: false
// },
{
reg: '^#?(我的)?记忆$',
fnc: 'showUserMemory'
},
{
reg: '^#?他的记忆$',
fnc: 'showTargetUserMemory'
},
{
reg: '^#?(删除|清除)(我的)?记忆\\s*(\\d+)$',
fnc: 'deleteUserMemory'
},
{
reg: '^#?(本群|群)记忆$',
fnc: 'showGroupMemory'
},
{
reg: '^#?(删除|移除)群记忆\\s*(\\d+)$',
fnc: 'deleteGroupMemory'
},
{
reg: `^${cmdPrefix}记忆列表$`,
fnc: 'adminMemoryOverview',
permission: 'master'
}
]
})
// 兼容miao和trss气死了
let task = {
name: 'ChatGPT-群记忆轮询',
cron: '*/1 * * * *',
fnc: this.pollHistoryTask.bind(this),
log: false
}
this.task = [task]
}
async collect (e) {
collector.push(e)
return false
}
async showUserMemory (e) {
if (!memoryService.isUserMemoryEnabled(e.sender.user_id)) {
await e.reply('私人记忆未开启或您未被授权。')
return false
}
const memories = memoryService.listUserMemories(e.sender.user_id, e.isGroup ? e.group_id : null)
if (!memories.length) {
await e.reply('🧠 您的记忆:\n暂无记录~')
return true
}
const msgs = memories.map(item =>
`${item.id}. ${item.value}(更新时间:${item.updated_at}`
)
const forwardMsg = await common.makeForwardMsg(e, ['🧠 您的记忆:', ...msgs], '私人记忆列表')
await e.reply(forwardMsg)
return true
}
async showTargetUserMemory (e) {
if (!e.isGroup) {
await e.reply('该指令仅可在群聊中使用。')
return false
}
const at = e.at || (e.message?.find(m => m.type === 'at')?.qq)
if (!at) {
await e.reply('请@要查询的用户。')
return false
}
if (!memoryService.isUserMemoryEnabled(at)) {
await e.reply('该用户未开启私人记忆或未被授权。')
return false
}
const memories = memoryService.listUserMemories(at, e.group_id)
if (!memories.length) {
await e.reply('🧠 TA的记忆\n暂无记录~')
return true
}
const msgs = memories.map(item =>
`${item.id}. ${item.value}(更新时间:${item.updated_at}`
)
const forwardMsg = await common.makeForwardMsg(e, ['🧠 TA的记忆', ...msgs], 'TA的记忆列表')
await e.reply(forwardMsg)
return true
}
async deleteUserMemory (e) {
const match = e.msg.match(/(\d+)$/)
if (!match) {
return false
}
const memoryId = Number(match[1])
if (!memoryId) {
return false
}
if (!memoryService.isUserMemoryEnabled(e.sender.user_id)) {
await e.reply('私人记忆未开启或您未被授权。')
return false
}
const success = memoryService.deleteUserMemory(memoryId, e.sender.user_id)
await e.reply(success ? '已删除指定记忆。' : '未找到对应的记忆条目。')
return success
}
async showGroupMemory (e) {
if (!e.isGroup) {
await e.reply('该指令仅可在群聊中使用。')
return false
}
if (!memoryService.isGroupMemoryEnabled(e.group_id)) {
await e.reply('本群尚未开启记忆功能。')
return false
}
await collector.flush(e.group_id)
const facts = memoryService.listGroupFacts(e.group_id)
if (!facts.length) {
await e.reply('📚 本群记忆:\n暂无群记忆。')
return true
}
const msgs = facts.map(item => {
const topic = item.topic ? `${item.topic}` : ''
return `${item.id}. ${topic}${item.fact}`
})
const forwardMsg = await common.makeForwardMsg(e, ['📚 本群记忆:', ...msgs], '群记忆列表')
await e.reply(forwardMsg)
return true
}
async deleteGroupMemory (e) {
if (!e.isGroup) {
await e.reply('该指令仅可在群聊中使用。')
return false
}
if (!memoryService.isGroupMemoryEnabled(e.group_id)) {
await e.reply('本群尚未开启记忆功能。')
return false
}
if (!isGroupManager(e)) {
await e.reply('仅限主人或群管理员管理群记忆。')
return false
}
await collector.flush(e.group_id)
const match = e.msg.match(/(\d+)$/)
if (!match) {
return false
}
const factId = Number(match[1])
if (!factId) {
return false
}
const success = memoryService.deleteGroupFact(e.group_id, factId)
await e.reply(success ? '已删除群记忆。' : '未找到对应的群记忆。')
return success
}
async adminMemoryOverview (e) {
const enabledGroups = (Config.memory?.group?.enabledGroups || []).map(String)
const groupLines = enabledGroups.length ? enabledGroups.join(', ') : '暂无'
const userStatus = Config.memory?.user?.enable ? '已启用' : '未启用'
await e.reply(`记忆系统概览:\n- 群记忆开关:${Config.memory?.group?.enable ? '已启用' : '未启用'}\n- 已启用群:${groupLines}\n- 私人记忆:${userStatus}`)
return true
}
async pollHistoryTask () {
try {
await collector.tickHistoryPolling()
} catch (err) {
logger.error('[Memory] scheduled history poll failed:', err)
}
return false
}
}

View file

@ -1,173 +0,0 @@
import plugin from '../../../lib/plugins/plugin.js'
import fs from 'fs'
import _ from 'lodash'
import { Config } from '../utils/config.js'
import {limitString, makeForwardMsg} from '../utils/common.js'
import { getPromptByName, readPrompts, saveOnePrompt } from '../utils/prompts.js'
export class help extends plugin {
constructor (e) {
super({
name: 'ChatGPT-Plugin 设定管理',
dsc: 'ChatGPT-Plugin 设定管理',
event: 'message',
priority: 500,
rule: [
{
reg: '^#(chatgpt|ChatGPT)设定列表$',
fnc: 'listPrompts',
permission: 'master'
},
{
reg: '^#(chatgpt|ChatGPT)查看设定',
fnc: 'detailPrompt',
permission: 'master'
},
{
reg: '^#(chatgpt|ChatGPT)使用设定',
fnc: 'usePrompt',
permission: 'master'
},
{
reg: '^#(chatgpt|ChatGPT)添加设定',
fnc: 'addPrompt',
permission: 'master'
},
{
reg: '^#(chatgpt|ChatGPT)(上传|分享|共享)设定',
fnc: 'uploadPrompt',
permission: 'master'
},
{
reg: '^#(chatgpt|ChatGPT)导入设定',
fnc: 'importPrompt',
permission: 'master'
},
{
reg: '^#(chatgpt|ChatGPT)设定帮助$',
fnc: 'helpPrompt',
permission: 'master'
}
]
})
}
async listPrompts (e) {
let prompts = []
let defaultPrompt = {
name: 'API默认',
content: Config.promptPrefixOverride
}
let defaultSydneyPrompt = {
name: 'Sydney默认',
content: Config.sydney
}
prompts.push(...[defaultPrompt, defaultSydneyPrompt])
prompts.push(...readPrompts())
console.log(prompts)
e.reply(await makeForwardMsg(e, prompts.map(p => `${p.name}\n${limitString(p.content, 500)}`), '设定列表'))
}
async detailPrompt (e) {
let promptName = e.msg.replace(/^#(chatgpt|ChatGPT)查看设定/, '').trim()
let prompt = getPromptByName(promptName)
if (!prompt) {
if (promptName === 'API默认') {
prompt = {
name: 'API默认',
content: Config.promptPrefixOverride
}
} else if (promptName === 'Sydney默认') {
prompt = {
name: 'Sydney默认',
content: Config.sydney
}
} else {
await e.reply('没有这个设定', true)
return
}
}
await e.reply(`${prompt.name}\n${limitString(prompt.content, 500)}`, true)
}
async usePrompt (e) {
let promptName = e.msg.replace(/^#(chatgpt|ChatGPT)使用设定/, '').trim()
let prompt = getPromptByName(promptName)
if (!prompt) {
console.log(promptName)
if (promptName === 'API默认') {
prompt = {
name: 'API默认',
content: Config.promptPrefixOverride
}
} else if (promptName === 'Sydney默认') {
prompt = {
name: 'Sydney默认',
content: Config.sydney
}
} else {
await e.reply('没有这个设定', true)
return
}
}
let use = await redis.get('CHATGPT:USE') || 'api'
if (use.toLowerCase() === 'bing') {
if (Config.toneStyle === 'Custom') {
use = 'Custom'
}
}
const keyMap = {
api: 'promptPrefixOverride',
Custom: 'sydney'
}
if (keyMap[use]) {
Config[keyMap[use]] = prompt.content
await redis.set(`CHATGPT:PROMPT_USE_${use}`, promptName)
await e.reply(`你当前正在使用${use}模式,已将该模式设定应用为"${promptName}。更该设定后建议结束对话以使设定更好生效"`, true)
} else {
await e.reply(`你当前正在使用${use}模式,该模式不支持设定`, true)
}
}
async addPrompt (e) {
this.setContext('addPromptName')
await e.reply('请输入设定名称', true)
}
async addPromptName () {
if (!this.e.msg) return
let name = this.e.msg
let prompt = getPromptByName(name)
if (prompt) {
await this.e.reply('该设定已存在', true)
this.finish('addPromptName')
return
}
await redis.set('CHATGPT:ADD_PROMPT_NAME', name)
await this.reply('请输入设定内容', true)
this.finish('addPromptName')
this.setContext('addPromptContext')
}
async addPromptContext () {
if (!this.e.msg) return
let content = this.e.msg
let name = await redis.get('CHATGPT:ADD_PROMPT_NAME')
saveOnePrompt(name, content)
await redis.del('CHATGPT:ADD_PROMPT_NAME')
await this.reply('设定添加成功', true)
this.finish('addPromptContext')
}
async uploadPrompt () {
await this.reply('敬请期待', true)
}
async importPrompt () {
await this.reply('敬请期待', true)
}
async helpPrompt () {
await this.reply('设定目录为/plugins/chatgpt-plugin/prompts将会读取该目录下的所有[设定名].txt文件作为设定列表', true)
}
}

350
apps/update.js Normal file
View file

@ -0,0 +1,350 @@
// modified from StarRail-plugin | 已经过StarRail-plugin作者本人同意
import plugin from '../../../lib/plugins/plugin.js'
import { createRequire } from 'module'
import _ from 'lodash'
import { Restart } from '../../other/restart.js'
import ChatGPTConfig from '../config/config.js'
const require = createRequire(import.meta.url)
const { exec, execSync } = require('child_process')
// 是否在更新中
let uping = false
/**
* 处理插件更新
*/
export class Update extends plugin {
constructor () {
const cmdPrefix = ChatGPTConfig.basic.commandPrefix
super({
name: 'chatgpt更新插件',
event: 'message',
priority: 1000,
rule: [
{
reg: `^${cmdPrefix}?(强制)?更新$`,
fnc: 'update'
}
]
})
}
/**
* rule - 更新chatgpt插件
* @returns
*/
async update () {
if (!this.e.isMaster) return false
/** 检查是否正在更新中 */
if (uping) {
await this.reply('已有命令更新中..请勿重复操作')
return
}
/** 检查git安装 */
if (!(await this.checkGit())) return
const isForce = this.e.msg.includes('强制')
/** 执行更新 */
await this.runUpdate(isForce)
/** 是否需要重启 */
if (this.isUp) {
// await this.reply("更新完毕,请重启云崽后生效")
setTimeout(() => this.restart(), 2000)
}
}
restart () {
new Restart(this.e).restart()
}
/**
* chatgpt插件更新函数
* @param {boolean} isForce 是否为强制更新
* @returns
*/
async runUpdate (isForce) {
try {
let command = 'git -C ./plugins/chatgpt-plugin/ pull --no-rebase'
if (isForce) {
command = `git -C ./plugins/chatgpt-plugin/ checkout . && ${command}`
this.e.reply('正在执行强制更新操作,请稍等')
} else {
this.e.reply('正在执行更新操作,请稍等')
}
/** 获取上次提交的commitId用于获取日志时判断新增的更新日志 */
this.oldCommitId = await this.getcommitId('chatgpt-plugin')
uping = true
let ret = await this.execSync(command)
if (ret.error) {
logger.mark(`${this.e.logFnc} 更新失败chatgpt-plugin`)
this.gitErr(ret.error, ret.stdout)
return false
}
// Check if pnpm is available
let packageManager = await this.checkPnpm()
await this.reply(`正在使用 ${packageManager} 更新 chaite 依赖...`)
let npmRet = await this.execSync(`cd ./plugins/chatgpt-plugin/ && ${packageManager} update chaite`)
logger.info(JSON.stringify(npmRet))
if (npmRet.error) {
logger.mark(`${this.e.logFnc} 更新失败chaite 依赖`)
await this.reply(`chaite 依赖更新失败:\n${npmRet.error.toString()}`)
return false
}
/** 获取插件提交的最新时间 */
let time = await this.getTime('chatgpt-plugin')
if (/(Already up[ -]to[ -]date|已经是最新的)/.test(ret.stdout)) {
await this.reply(`chatgpt-plugin已经是最新版本\n最后更新时间:${time}`)
} else {
let updateMsg = `chatgpt-plugin\n最后更新时间:${time}`
// Add npm update information if available
if (npmRet.stdout.includes('chaite')) {
updateMsg += `\n已使用${packageManager}更新chaite依赖`
}
await this.reply(updateMsg)
this.isUp = true
/** 获取chatgpt组件的更新日志 */
let log = await this.getLog('chatgpt-plugin')
await this.reply(log)
}
logger.mark(`${this.e.logFnc} 最后更新时间:${time}`)
return true
} catch (err) {
logger.error(err)
await this.reply(`更新失败:\n${err.toString()}`)
return false
} finally {
uping = false
}
}
/**
* 获取chatgpt插件的更新日志
* @param {string} plugin 插件名称
* @returns
*/
async getLog (plugin = '') {
let cm = `cd ./plugins/${plugin}/ && git log -20 --oneline --pretty=format:"%h||[%cd] %s" --date=format:"%m-%d %H:%M"`
let logAll
try {
logAll = await execSync(cm, { encoding: 'utf-8' })
} catch (error) {
logger.error(error.toString())
this.reply(error.toString())
}
if (!logAll) return false
logAll = logAll.split('\n')
let log = []
for (let str of logAll) {
str = str.split('||')
if (str[0] == this.oldCommitId) break
if (str[1].includes('Merge branch')) continue
log.push(str[1])
}
let line = log.length
log = log.join('\n\n')
if (log.length <= 0) return ''
let end = ''
end =
'更多详细信息请前往github查看\nhttps://github.com/ikechan8370/chatgpt-plugin'
log = await this.makeForwardMsg(`chatgpt-plugin更新日志${line}`, log, end)
return log
}
/**
* 获取上次提交的commitId
* @param {string} plugin 插件名称
* @returns
*/
async getcommitId (plugin = '') {
let cm = `git -C ./plugins/${plugin}/ rev-parse --short HEAD`
let commitId = await execSync(cm, { encoding: 'utf-8' })
commitId = _.trim(commitId)
return commitId
}
/**
* 获取本次更新插件的最后一次提交时间
* @param {string} plugin 插件名称
* @returns
*/
async getTime (plugin = '') {
let cm = `cd ./plugins/${plugin}/ && git log -1 --oneline --pretty=format:"%cd" --date=format:"%m-%d %H:%M"`
let time = ''
try {
time = await execSync(cm, { encoding: 'utf-8' })
time = _.trim(time)
} catch (error) {
logger.error(error.toString())
time = '获取时间失败'
}
return time
}
/**
* 制作转发消息
* @param {string} title 标题 - 首条消息
* @param {string} msg 日志信息
* @param {string} end 最后一条信息
* @returns
*/
async makeForwardMsg (title, msg, end) {
const _bot = this.e.bot ?? Bot
let nickname = _bot.nickname
if (this.e.isGroup) {
let info = await _bot?.pickMember?.(this.e.group_id, _bot.uin) || await _bot?.getGroupMemberInfo?.(this.e.group_id, _bot.uin)
nickname = info.card || info.nickname
}
let userInfo = {
user_id: _bot.uin,
nickname
}
let forwardMsg = [
{
...userInfo,
message: title
},
{
...userInfo,
message: msg
}
]
if (end) {
forwardMsg.push({
...userInfo,
message: end
})
}
/** 制作转发内容 */
if (this.e.group?.makeForwardMsg) {
forwardMsg = await this.e.group.makeForwardMsg(forwardMsg)
} else if (this.e?.friend?.makeForwardMsg) {
forwardMsg = await this.e.friend.makeForwardMsg(forwardMsg)
} else {
return msg.join('\n')
}
let dec = 'chatgpt-plugin 更新日志'
/** 处理描述 */
if (typeof (forwardMsg.data) === 'object') {
let detail = forwardMsg.data?.meta?.detail
if (detail) {
detail.news = [{ text: dec }]
}
} else {
forwardMsg.data = forwardMsg.data
.replace(/\n/g, '')
.replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___')
.replace(/___+/, `<title color="#777777" size="26">${dec}</title>`)
}
return forwardMsg
}
/**
* 检查是否安装pnpm
* @returns {Promise<string>} 返回 'pnpm' 'npm'
*/
async checkPnpm () {
let npm = 'npm'
let ret = await this.execSync('pnpm -v')
if (ret.stdout) npm = 'pnpm'
return npm
}
/**
* 处理更新失败的相关函数
* @param {string} err
* @param {string} stdout
* @returns
*/
async gitErr (err, stdout) {
let msg = '更新失败!'
let errMsg = err.toString()
stdout = stdout.toString()
if (errMsg.includes('Timed out')) {
let remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '')
await this.reply(msg + `\n连接超时:${remote}`)
return
}
if (/Failed to connect|unable to access/g.test(errMsg)) {
let remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '')
await this.reply(msg + `\n连接失败:${remote}`)
return
}
if (errMsg.includes('be overwritten by merge')) {
await this.reply(
msg +
`存在冲突:\n${errMsg}\n` +
'请解决冲突后再更新,或者执行#强制更新,放弃本地修改'
)
return
}
if (stdout.includes('CONFLICT')) {
await this.reply([
msg + '存在冲突\n',
errMsg,
stdout,
'\n请解决冲突后再更新或者执行#强制更新,放弃本地修改'
])
return
}
await this.reply([errMsg, stdout])
}
/**
* 异步执行git相关命令
* @param {string} cmd git命令
* @returns
*/
async execSync (cmd) {
return new Promise((resolve, reject) => {
exec(cmd, { windowsHide: true }, (error, stdout, stderr) => {
resolve({ error, stdout, stderr })
})
})
}
/**
* 检查git是否安装
* @returns
*/
async checkGit () {
let ret = await execSync('git --version', { encoding: 'utf-8' })
if (!ret || !ret.includes('git version')) {
await this.reply('请先安装git')
return false
}
return true
}
}

View file

@ -1,21 +0,0 @@
{
"apiKey": "",
"proxy": "",
"openAiBaseUrl": "https://mondstadt.d201.eu.org/v1",
"api": "https://pimon.d201.cn/backend-api/conversation",
"apiBaseUrl": "https://pimon.d201.cn/backend-api",
"promptPrefixOverride": "Your answer shouldn't be too verbose. If you are generating a list, do not have too many items. Keep the number of items short. Prefer to answer in Chinese.",
"debug": false,
"blockWords": ["屏蔽词1", "屏蔽词b"],
"promptBlockWords": ["屏蔽词1", "屏蔽词b"],
"imgOcr": true,
"defaultUsePicture": false,
"autoUsePicture": true,
"autoUsePictureThreshold": 1200,
"toggleMode": "at",
"quoteReply": true,
"showQRCode": true,
"cacheUrl": "https://content.alcedogroup.com",
"cacheEntry": false,
"drawCD": 30
}

587
config/config.js Normal file
View file

@ -0,0 +1,587 @@
import fs from 'fs'
import path from 'path'
import yaml from 'js-yaml'
class ChatGPTConfig {
/**
* 版本号
* @type {string}
*/
version = '3.0.0'
/**
* 基本配置
* @type {{
* toggleMode: 'at' | 'prefix',
* debug: boolean,
* }}
*/
basic = {
// 触发方式at触发或者前缀触发
toggleMode: 'at',
// 触发前缀,仅在前缀触发时有效
togglePrefix: '#chat',
// 是否开启调试模式
debug: false,
// 一般命令的开头
commandPrefix: '#chatgpt'
}
/**
* 伪人模式基于框架实现因此机器人开启前缀后依然需要带上前缀
* @type {{
* enable: boolean,
* hit: string[],
* probability: number,
* defaultPreset: string,
* presetPrefix?: string,
* presetMap: Array<{
* keywords: string[],
* presetId: string,
* priority: number,
* recall?: boolean
* }>,
* maxTokens: number,
* temperature: number,
* sendReasoning: boolean
* }}
* }}
*/
bym = {
// 开关
enable: false,
// 伪人必定触发词
hit: ['bym'],
// 不包含伪人必定触发词时的概率
probability: 0.02,
// 伪人模式的默认预设
defaultPreset: '',
// 伪人模式的预设前缀会加在在所有其他预设前。例如此处可以用于配置通用的伪人发言风格随意、模仿群友等presetMap中专心配置角色设定即可
presetPrefix: '',
// 包含关键词与预设的对应关系。包含特定触发词使用特定的预设,按照优先级排序
presetMap: [],
// 如果大于0会覆盖preset中的maxToken用于控制伪人模式发言长度
maxTokens: 0,
// 如果大于等于0会覆盖preset中的temperature用于控制伪人模式发言随机性
temperature: -1,
// 是否发送思考内容
sendReasoning: false
}
/**
* 模型和对话相关配置
* @type {{
* defaultModel: string,
* embeddingModel: string,
* defaultChatPresetId: string,
* enableCustomPreset: boolean,
* customPresetUserWhiteList: string[],
* customPresetUserBlackList: string[],
* promptBlockWords: string[],
* responseBlockWords: string[],
* blockStrategy: 'full' | 'mask',
* blockWordMask: string,
* enableGroupContext: boolean,
* groupContextLength: number,
* groupContextTemplatePrefix: string,
* groupContextTemplateMessage: string,
* groupContextTemplateSuffix: string
* }}
*/
llm = {
// 默认模型,初始化构建预设使用
defaultModel: '',
// 嵌入模型
embeddingModel: 'gemini-embedding-exp-03-07',
// 嵌入结果维度0表示自动
dimensions: 0,
// 默认对话预设ID
defaultChatPresetId: '',
// 是否启用允许其他人切换预设
enableCustomPreset: false,
// 允许切换预设的用户白名单
customPresetUserWhiteList: [],
// 禁止切换预设的用户黑名单
customPresetUserBlackList: [],
// 用户对话屏蔽词
promptBlockWords: [],
// 机器人回复屏蔽词
responseBlockWords: [],
// 触发屏蔽词的策略,完全屏蔽或仅屏蔽关键词
blockStrategy: 'full',
// 如果blockStrategy为mask屏蔽词的替换字符
blockWordMask: '***',
// 是否开启群组上下文
enableGroupContext: false,
// 群组上下文长度
groupContextLength: 20,
// 用于组装群聊上下文提示词的模板前缀
groupContextTemplatePrefix: '<settings>\n' +
// eslint-disable-next-line no-template-curly-in-string
'You are a member of a chat group, whose name is ${group.name}, and the group id is ${group.id}.\n' +
'</settings>Latest several messages in the group chat:\n' +
' 群名片 | 昵称 | qq号 | 群角色 | 群头衔 | 时间 | messageId | 消息内容 |\n' +
'|---|---|---|---|---|---|---|---|',
// 用于组装群聊上下文提示词的模板内容部分每一条消息作为message仿照示例填写
// eslint-disable-next-line no-template-curly-in-string
groupContextTemplateMessage: '| ${message.sender.card} | ${message.sender.nickname} | ${message.sender.user_id} | ${message.sender.role} | ${message.sender.title} | ${message.time} | ${message.messageId} | ${message.raw_message} |',
// 用于组装群聊上下文提示词的模板后缀
groupContextTemplateSuffix: '\n'
}
/**
* 管理相关配置
* @type {{
* blackGroups: number[],
* whiteGroups: number[],
* blackUsers: string[],
* whiteUsers: string[],
* defaultRateLimit: number
* }}
*/
management = {
blackGroups: [],
whiteGroups: [],
blackUsers: [],
whiteUsers: [],
// 默认对话速率限制0表示不限制数字表示每分钟最多对话次数
defaultRateLimit: 0
}
/**
* chaite相关配置
* @type {
* { dataDir: string,
* processorsDirPath: string,
* toolsDirPath: string,
* cloudBaseUrl: string,
* cloudApiKey: string,
* authKey: string,
* host: string,
* port: number}}
*/
chaite = {
// 数据目录,相对于插件下
dataDir: 'data',
// 处理器目录,相对于插件下
processorsDirPath: 'utils/processors',
// 触发器目录,相对于插件目录下
triggersDir: 'utils/triggers',
// 工具目录,相对于插件目录下
toolsDirPath: 'utils/tools',
// 云端API url
cloudBaseUrl: 'https://api.chaite.cloud',
// 云端API Key
cloudApiKey: '',
// jwt key非必要勿修改修改需重启
authKey: '',
// 管理面板监听地址
host: '0.0.0.0',
// 管理面板监听端口
port: 48370,
// 存储实现 sqlite lowdb
storage: 'sqlite'
}
/**
* 记忆系统配置
* @type {{
* database: string,
* vectorDimensions: number,
* group: {
* enable: boolean,
* enabledGroups: string[],
* extractionModel: string,
* extractionPresetId: string,
* minMessageCount: number,
* maxMessageWindow: number,
* retrievalMode: 'vector' | 'keyword' | 'hybrid',
* hybridPrefer: 'vector-first' | 'keyword-first',
* historyPollInterval: number,
* historyBatchSize: number,
* promptHeader: string,
* promptItemTemplate: string,
* promptFooter: string,
* extractionSystemPrompt: string,
* extractionUserPrompt: string,
* vectorMaxDistance: number,
* textMaxBm25Score: number,
* maxFactsPerInjection: number,
* minImportanceForInjection: number
* },
* user: {
* enable: boolean,
* whitelist: string[],
* blacklist: string[],
* extractionModel: string,
* extractionPresetId: string,
* maxItemsPerInjection: number,
* maxRelevantItemsPerQuery: number,
* minImportanceForInjection: number,
* promptHeader: string,
* promptItemTemplate: string,
* promptFooter: string,
* extractionSystemPrompt: string,
* extractionUserPrompt: string
* },
* extensions: {
* simple: {
* enable: boolean,
* libraryPath: string,
* dictPath: string,
* useJieba: boolean
* }
* }
* }}
*/
memory = {
database: 'data/memory.db',
vectorDimensions: 1536,
group: {
enable: false,
enabledGroups: [],
extractionModel: '',
extractionPresetId: '',
minMessageCount: 80,
maxMessageWindow: 300,
retrievalMode: 'hybrid',
hybridPrefer: 'vector-first',
historyPollInterval: 300,
historyBatchSize: 120,
promptHeader: '# 以下是一些该群聊中可能相关的事实,你可以参考,但不要主动透露这些事实。',
promptItemTemplate: '- ${fact}${topicSuffix}${timeSuffix}',
promptFooter: '',
extractionSystemPrompt: `You are a knowledge extraction assistant that specialises in summarising long-term facts from group chat transcripts.
Read the provided conversation and identify statements that should be stored as long-term knowledge for the group.
Return a JSON array. Each element must contain:
{
"fact": 事实内容必须完整包含事件的各个要素而不能是简单的短语比如谁参与了事件做了什么事情背景时间是什么同一件事情尽可能整合为同一条而非拆分以便利于检索,
"topic": 主题关键词字符串 "活动""成员信息",
"importance": 一个介于0和1之间的小数数值越大表示越重要,
"source_message_ids": 原始消息ID数组,
"source_messages": 对应原始消息的简要摘录或合并文本,
"involved_users": 出现或相关的用户ID数组
}
Only include meaningful, verifiable group-specific information that is useful for future conversations. Do not record incomplete information. Do not include general knowledge or unrelated facts. Do not wrap the JSON array in code fences.`,
extractionUserPrompt: `以下是群聊中的一些消息请根据系统说明提取值得长期记忆的事实以JSON数组形式返回不要输出额外说明。
\${messages}`,
vectorMaxDistance: 0,
textMaxBm25Score: 0,
maxFactsPerInjection: 5,
minImportanceForInjection: 0.3
},
user: {
enable: false,
whitelist: [],
blacklist: [],
extractionModel: '',
extractionPresetId: '',
maxItemsPerInjection: 5,
maxRelevantItemsPerQuery: 3,
minImportanceForInjection: 0,
promptHeader: '# 用户画像',
promptItemTemplate: '- ${value}${timeSuffix}',
promptFooter: '',
extractionSystemPrompt: `You are an assistant that extracts long-term personal preferences or persona details about a user.
Given a conversation snippet between the user and the bot, identify durable information such as preferences, nicknames, roles, speaking style, habits, or other facts that remain valid over time.
Return a JSON array of **strings**, and nothing else, without any other characters including \`\`\` or \`\`\`json. Each string must be a short sentence (in the same language as the conversation) describing one piece of long-term memory. Do not include keys, JSON objects, or additional metadata. Ignore temporary topics or uncertain information.`,
extractionUserPrompt: `下面是用户与机器人的对话,请根据系统提示提取可长期记忆的个人信息。
\${messages}`
},
extensions: {
simple: {
enable: false,
libraryPath: '',
dictPath: '',
useJieba: false
}
}
}
constructor () {
this.version = '3.0.0'
this.watcher = null
this.configPath = ''
}
/**
* Start config file sync
* call once!
* @param {string} configDir Directory containing config files
*/
startSync (configDir) {
// 配置路径设置
const jsonPath = path.join(configDir, 'config.json')
const yamlPath = path.join(configDir, 'config.yaml')
if (fs.existsSync(jsonPath)) {
this.configPath = jsonPath
} else if (fs.existsSync(yamlPath)) {
this.configPath = yamlPath
} else {
this.configPath = jsonPath
this.saveToFile()
}
// 加载初始配置
this.loadFromFile()
// 文件变更标志和保存定时器
this._saveOrigin = null
this._saveTimer = null
// 监听文件变化
this.watcher = fs.watchFile(this.configPath, (curr, prev) => {
if (curr.mtime !== prev.mtime && this._saveOrigin !== 'code') {
this.loadFromFile()
}
})
// 处理所有嵌套对象
return this._createProxyRecursively(this)
}
// 递归创建代理
_createProxyRecursively (obj, path = []) {
if (obj === null || typeof obj !== 'object' || obj instanceof Date) {
return obj
}
// 处理数组和对象
if (Array.isArray(obj)) {
// 创建一个新数组,递归地处理每个元素
const proxiedArray = [...obj].map((item, index) =>
this._createProxyRecursively(item, [...path, index])
)
// 代理数组,捕获数组方法调用
return new Proxy(proxiedArray, {
set: (target, prop, value) => {
// 处理数字属性(数组索引)和数组长度
if (typeof prop !== 'symbol' &&
((!isNaN(prop) && prop !== 'length') ||
prop === 'length')) {
// 直接设置值
target[prop] = value
// 触发保存
this._triggerSave('array')
} else {
target[prop] = value
}
return true
},
// 拦截数组方法调用
get: (target, prop) => {
const val = target[prop]
// 处理数组修改方法
if (typeof val === 'function' &&
['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].includes(prop)) {
return function (...args) {
const result = Array.prototype[prop].apply(target, args)
// 方法调用后触发保存
this._triggerSave('array-method')
return result
}.bind(this)
}
return val
}
})
} else {
// 对普通对象的处理
const proxiedObj = {}
// 处理所有属性
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
// 跳过内部属性
if (key === 'watcher' || key === 'configPath' ||
key.startsWith('_save') || key === '_isSaving') {
proxiedObj[key] = obj[key]
} else {
// 递归处理嵌套对象
proxiedObj[key] = this._createProxyRecursively(
obj[key], [...path, key]
)
}
}
}
// 创建对象的代理
return new Proxy(proxiedObj, {
set: (target, prop, value) => {
// 跳过内部属性的处理
if (prop === 'watcher' || prop === 'configPath' ||
prop.startsWith('_save') || prop === '_isSaving') {
target[prop] = value
return true
}
// 设置新值,如果是对象则递归创建代理
if (value !== null && typeof value === 'object') {
target[prop] = this._createProxyRecursively(
value, [...path, prop]
)
} else {
target[prop] = value
}
// 触发保存
this._triggerSave('object')
return true
}
})
}
}
loadFromFile () {
try {
if (!fs.existsSync(this.configPath)) {
// 如果文件不存在,直接返回
return
}
const content = fs.readFileSync(this.configPath, 'utf8')
const loadedConfig = this.configPath.endsWith('.json')
? JSON.parse(content)
: yaml.load(content)
// 处理加载的配置并和默认值合并
if (loadedConfig) {
const mergeResult = this._mergeConfig(loadedConfig)
if (mergeResult.changed) {
logger?.debug?.('[Config] merged new defaults into persisted config; scheduling save')
this._triggerSave('code')
}
}
logger.debug('Config loaded successfully')
} catch (error) {
logger.error('Failed to load config:', error)
}
}
_mergeConfig (loadedConfig) {
let changed = false
const mergeInto = (target, source) => {
if (!source || typeof source !== 'object') {
return target
}
if (!target || typeof target !== 'object') {
target = Array.isArray(source) ? [] : {}
}
const result = Array.isArray(source) ? [] : { ...target }
if (Array.isArray(source)) {
return source.slice()
}
const targetKeys = target && typeof target === 'object'
? Object.keys(target)
: []
for (const key of targetKeys) {
if (!Object.prototype.hasOwnProperty.call(source, key)) {
changed = true
}
}
for (const key of Object.keys(source)) {
const sourceValue = source[key]
const targetValue = target[key]
if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) {
result[key] = mergeInto(targetValue, sourceValue)
} else {
if (targetValue === undefined || targetValue !== sourceValue) {
changed = true
}
result[key] = sourceValue
}
}
return result
}
const sections = ['version', 'basic', 'bym', 'llm', 'management', 'chaite', 'memory']
for (const key of sections) {
const loadedValue = loadedConfig[key]
if (loadedValue === undefined) {
continue
}
if (typeof loadedValue === 'object' && loadedValue !== null) {
const merged = mergeInto(this[key], loadedValue)
if (merged !== this[key]) {
this[key] = merged
}
} else {
if (this[key] !== loadedValue) {
changed = true
}
this[key] = loadedValue
}
}
return { changed }
}
// 合并触发保存,防抖处理
_triggerSave (origin) {
// 清除之前的定时器
if (this._saveTimer) {
clearTimeout(this._saveTimer)
}
const originLabel = origin || 'code'
this._saveOrigin = originLabel
this._saveTimer = setTimeout(() => {
this.saveToFile(originLabel)
this._saveOrigin = null
}, 200)
}
saveToFile (origin = 'code') {
if (origin !== 'code') {
this._saveOrigin = 'external'
}
logger.debug('Saving config to file...')
try {
const config = {
version: this.version,
basic: this.basic,
bym: this.bym,
llm: this.llm,
management: this.management,
chaite: this.chaite,
memory: this.memory
}
const content = this.configPath.endsWith('.json')
? JSON.stringify(config, null, 2)
: yaml.dump(config)
fs.writeFileSync(this.configPath, content, 'utf8')
} catch (error) {
console.error('Failed to save config:', error)
}
}
toJSON () {
return {
version: this.version,
basic: this.basic,
bym: this.bym,
llm: this.llm,
management: this.management,
chaite: this.chaite,
memory: this.memory
}
}
}
export default new ChatGPTConfig()

View file

@ -1,3 +0,0 @@
## 配置项解析
正在施工中......

View file

@ -1,6 +1,4 @@
import { Config } from './utils/config.js'
import { speakers } from './utils/tts.js'
import Config from './config/config.js'
// 支持锅巴
export function supportGuoba () {
return {
@ -27,440 +25,12 @@ export function supportGuoba () {
// 配置项 schemas
schemas: [
{
field: 'blockWords',
label: '输出黑名单',
bottomHelpMessage: '检查输出结果中是否有违禁词,如果存在黑名单中的违禁词则不输出',
component: 'InputTextArea'
},
{
field: 'promptBlockWords',
label: '输入黑名单',
bottomHelpMessage: '检查输入结果中是否有违禁词,如果存在黑名单中的违禁词则不输出',
component: 'InputTextArea'
},
{
field: 'imgOcr',
label: '图片识别',
bottomHelpMessage: '是否识别消息中图片的文字内容,需要同时包含图片和消息才生效',
component: 'Switch'
},
{
field: 'defaultUsePicture',
label: '全局图片模式',
bottomHelpMessage: '全局默认以图片形式回复。',
component: 'Switch'
},
{
field: 'defaultUseTTS',
label: '全局语音模式',
bottomHelpMessage: '全局默认以语音形式回复,使用默认角色音色。',
component: 'Switch'
},
{
field: 'defaultTTSRole',
label: '语音模式默认角色',
bottomHelpMessage: '语音模式下,未指定角色时使用的角色。若留空,将使用随机角色回复。若用户通过指令指定了角色,将忽略本设定',
component: 'Select',
componentProps: {
options: speakers.concat('随机').map(s => { return { label: s, value: s } })
field: 'testRender',
label: '表格测试',
component: 'Render',
render: () => {
`<span>你好</span>`
}
},
{
field: 'ttsAutoFallbackThreshold',
label: '语音转文字阈值',
helpMessage: '语音模式下,字数超过这个阈值就降级为文字',
bottomHelpMessage: '语音转为文字的阈值。',
component: 'InputNumber',
componentProps: {
min: 0,
max: 299
}
},
{
field: 'alsoSendText',
label: '语音同时发送文字',
bottomHelpMessage: '语音模式下,同时发送文字版,避免音质较低听不懂',
component: 'Switch'
},
{
field: 'autoUsePicture',
label: '长文本自动转图片',
bottomHelpMessage: '字数大于阈值会自动用图片发送,即使是文本模式。',
component: 'Switch'
},
{
field: 'autoUsePictureThreshold',
label: '自动转图片阈值',
helpMessage: '长文本自动转图片开启后才生效',
bottomHelpMessage: '自动转图片的字数阈值。',
component: 'InputNumber',
componentProps: {
min: 0
}
},
{
field: 'conversationPreserveTime',
label: '对话保留时长',
helpMessage: '单位:秒',
bottomHelpMessage: '每个人发起的对话保留时长。超过这个时长没有进行对话,再进行对话将开启新的对话。',
component: 'InputNumber',
componentProps: {
min: 0
}
},
{
field: 'toggleMode',
label: '触发方式',
bottomHelpMessage: 'at模式下只有at机器人才会回复。#chat模式下不需要at但需要添加前缀#chat。',
component: 'Select',
componentProps: {
options: [
{ label: 'at', value: 'at' },
{ label: '#chat', value: 'prefix' }
]
}
},
{
field: 'allowOtherMode',
label: '允许其他模式',
bottomHelpMessage: '开启后,则允许用户使用#chat1/#chat3/#chatglm/#bing等命令无视全局模式进行聊天',
component: 'Switch'
},
{
field: 'quoteReply',
label: '图片引用消息',
bottomHelpMessage: '在回复图片时引用原始消息',
component: 'Switch'
},
{
field: 'showQRCode',
label: '启用二维码',
bottomHelpMessage: '在图片模式中启用二维码。该对话内容将被发送至第三方服务器以进行渲染展示,如果不希望对话内容被上传到第三方服务器请关闭此功能。',
component: 'Switch'
},
{
field: 'cacheUrl',
label: '渲染服务器地址',
bottomHelpMessage: '用于缓存图片模式会话内容并渲染的服务器地址。',
component: 'Input'
},
{
field: 'cacheEntry',
label: '预制渲染服务器访问代码',
bottomHelpMessage: '图片内容渲染服务器开启预制访问代码,当渲染服务器访问较慢时可以开启,但无法保证访问代码可以正常访问页面。',
component: 'Switch'
},
{
field: 'drawCD',
label: '绘图CD',
helpMessage: '单位:秒',
bottomHelpMessage: '绘图指令的CD时间主人不受限制',
component: 'InputNumber',
componentProps: {
min: 0
}
},
{
field: 'enableDraw',
label: '绘图功能开关',
component: 'Switch'
},
{
field: 'proxy',
label: '代理服务器地址',
bottomHelpMessage: '数据通过代理服务器发送http或socks5代理。',
component: 'Input'
},
{
field: 'debug',
label: '调试信息',
bottomHelpMessage: '将输出更多调试信息,如果不希望控制台刷屏的话,可以关闭。',
component: 'Switch'
},
{
label: '以下为服务超时配置。',
component: 'Divider'
},
{
field: 'defaultTimeoutMs',
label: '默认超时时间',
helpMessage: '单位:毫秒',
bottomHelpMessage: '各个地方的默认超时时间。',
component: 'InputNumber',
componentProps: {
min: 0
}
},
{
field: 'chromeTimeoutMS',
label: '浏览器超时时间',
helpMessage: '单位:毫秒',
bottomHelpMessage: '浏览器默认超时,浏览器可能需要更高的超时时间。',
component: 'InputNumber',
componentProps: {
min: 0
}
},
{
field: 'sydneyFirstMessageTimeout',
label: 'Sydney模式接受首条信息超时时间',
helpMessage: '单位:毫秒',
bottomHelpMessage: '超过该时间阈值未收到Bing的任何消息则断开本次连接并重试最多重试3次失败后返回timeout waiting for first message。',
component: 'InputNumber',
componentProps: {
min: 15000
}
},
{
label: '以下为API方式(默认)的配置',
component: 'Divider'
},
{
field: 'apiKey',
label: 'OpenAI API Key',
bottomHelpMessage: 'OpenAI的ApiKey用于访问OpenAI的API接口。',
component: 'InputPassword'
},
{
field: 'openAiBaseUrl',
label: 'OpenAI API服务器地址',
bottomHelpMessage: 'OpenAI的API服务器地址。注意要带上/v1。默认为https://api.openai.com/v1',
component: 'Input'
},
{
field: 'openAiForceUseReverse',
label: '强制使用OpenAI反代',
bottomHelpMessage: '即使配置了proxy依然使用OpenAI反代',
component: 'Switch'
},
{
field: 'promptPrefixOverride',
label: 'AI风格',
bottomHelpMessage: '你可以在这里写入你希望AI回答的风格比如希望优先回答中文回答长一点等。',
component: 'InputTextArea'
},
{
field: 'assistantLabel',
label: 'AI名字',
bottomHelpMessage: 'AI认为的自己的名字当你问他你是谁是他会回答这里的名字。',
component: 'Input'
},
{
field: 'temperature',
label: 'temperature',
bottomHelpMessage: '用于控制回复内容的多样性,数值越大回复越加随机、多元化,数值越小回复越加保守。',
component: 'InputNumber',
componentProps: {
min: 0,
max: 2
}
},
{
label: '以下为必应方式的配置。',
component: 'Divider'
},
{
field: 'toneStyle',
label: 'Bing模式',
bottomHelpMessage: '微软必应官方的三种应答风格。默认为均衡Sydney为实验风格独立与三种风格之外。',
component: 'Select',
componentProps: {
options: [
{ label: '均衡', value: 'balanced' },
{ label: '创意', value: 'creative' },
{ label: '精确', value: 'precise' },
{ label: 'Sydney(可能存在风险)', value: 'Sydney' },
{ label: '自设定(可能存在风险)', value: 'Custom' }
]
}
},
{
field: 'enableSuggestedResponses',
label: '是否开启建议回复',
bottomHelpMessage: '开启了会像官网上一样,每个问题给出建议的用户问题',
component: 'Switch'
},
{
field: 'sydney',
label: 'Custom的设定',
bottomHelpMessage: '仅自设定模式下有效。你可以自己改写设定让Sydney变成你希望的样子。可能存在不稳定的情况。',
component: 'InputTextArea'
},
{
field: 'sydneyContext',
label: 'Bing的扩展资料',
bottomHelpMessage: 'AI将会从你提供的扩展资料中学习到一些知识帮助它更好地回答你的问题。实际相当于使用edge侧边栏Bing时读取的你当前浏览网页的内容。如果太长可能容易到达GPT-4的8192token上限。',
component: 'InputTextArea'
},
{
field: 'sydneyReverseProxy',
label: 'sydney反代',
bottomHelpMessage: '仅自设定模式下有效。国内ip无法正常使用sydney和自设定模式如果有bing.com的反代可以填在此处或者使用proxy',
component: 'Input'
},
{
field: 'sydneyForceUseReverse',
label: '强制使用sydney反代',
bottomHelpMessage: '即使配置了proxy依然使用sydney反代',
component: 'Switch'
},
{
field: 'sydneyBrainWash',
label: '开启强制洗脑',
bottomHelpMessage: '仅自设定模式下有效。如果发现自设定模式下总是回复类似于换个话题之类的话,可以开启强制洗脑试试,如果还不行就调整你的设定',
component: 'Switch'
},
{
field: 'sydneyBrainWashName',
label: 'Custom模式下的称呼',
bottomHelpMessage: '仅自设定模式下有效。如果开启了强制洗脑,务必准确填写这个才能精准洗脑。不开启洗脑可以不管这个',
component: 'Input'
},
{
field: 'sydneyBrainWashStrength',
label: '洗脑强度',
bottomHelpMessage: '仅自设定模式下有效。洗脑强度。默认为15可以酌情调整。太大的话可能长对话会影响对话质量',
component: 'InputNumber',
componentProps: {
min: 0,
max: 100
}
},
{
label: '以下为API3方式的配置。',
component: 'Divider'
},
{
field: 'api',
label: 'ChatGPT API反代服务器地址',
bottomHelpMessage: 'ChatGPT的API反代服务器用于绕过Cloudflare访问ChatGPT API',
component: 'Input'
},
{
field: 'apiBaseUrl',
label: 'apiBaseUrl地址',
bottomHelpMessage: 'apiBaseUrl地址',
component: 'Input'
},
{
field: 'apiForceUseReverse',
label: '强制使用ChatGPT反代',
bottomHelpMessage: '即使配置了proxy依然使用ChatGPT反代',
component: 'Switch'
},
{
field: 'useGPT4',
label: '使用GPT-4',
bottomHelpMessage: '使用GPT-4注意试用配额较低如果用不了就关掉',
component: 'Switch'
},
{
label: '以下为浏览器方式的配置.(Deprecated)',
component: 'Divider'
},
{
field: 'username',
label: '用户名',
bottomHelpMessage: 'OpenAI用户名。',
component: 'Input'
},
{
field: 'password',
label: '密码',
bottomHelpMessage: 'OpenAI密码。',
component: 'InputPassword'
},
{
field: 'UA',
label: '浏览器UA',
bottomHelpMessage: '模拟浏览器UA无特殊需求保持默认即可。',
component: 'InputTextArea'
},
{
field: 'headless',
label: '无头模式',
bottomHelpMessage: '无界面的服务器可以开启,但遇到验证码时可能无法使用。(实测很容易卡住,几乎不可用)。',
component: 'Switch'
},
{
field: 'chromePath',
label: 'Chrome路径',
bottomHelpMessage: '为空使用默认puppeteer的chromium也可以传递自己本机安装的Chrome可执行文件地址提高通过率。windows可以是C:\\Program Files\\Google\\Chrome\\Application\\chrome.exelinux通过which查找路径。',
component: 'Input'
},
{
label: '以下为ChatGLM方式的配置',
component: 'Divider'
},
{
field: 'chatglmBaseUrl',
label: 'ChatGLM API地址',
bottomHelpMessage: '如 http://localhost:8080',
component: 'Input'
},
{
label: '以下为杂七杂八的配置',
component: 'Divider'
},
{
field: '2captchaToken',
label: '验证码平台Token',
bottomHelpMessage: '可注册2captcha实现跳过验证码收费服务但很便宜。否则可能会遇到验证码而卡住。',
component: 'InputPassword'
},
{
field: 'ttsSpace',
label: '语音转换API地址',
bottomHelpMessage: '前往duplicate空间https://huggingface.co/spaces/ikechan8370/vits-uma-genshin-honkai后查看api地址',
component: 'Input'
},
{
field: 'huggingFaceReverseProxy',
label: '语音转换huggingface反代',
bottomHelpMessage: '没有就空着',
component: 'Input'
},
{
field: 'noiseScale',
label: 'noiseScale',
bottomHelpMessage: '控制情感变化程度',
component: 'InputNumber',
componentProps: {
min: 0,
max: 1
}
},
{
field: 'noiseScaleW',
label: 'noiseScaleW',
bottomHelpMessage: '控制音素发音长度',
component: 'InputNumber',
componentProps: {
min: 0,
max: 1
}
},
{
field: 'lengthScale',
label: 'lengthScale',
bottomHelpMessage: '控制整体语速',
component: 'InputNumber',
componentProps: {
min: 0,
max: 2
}
},
{
field: 'initiativeChatGroups',
label: '主动发起聊天群聊的群号',
bottomHelpMessage: '在这些群聊里会不定时主动说一些随机的打招呼的话用英文逗号隔开。必须配置了OpenAI Key',
component: 'Input'
},
{
field: 'helloPrompt',
label: '打招呼所说文字的引导文字',
bottomHelpMessage: '将会用这段文字询问ChatGPT由ChatGPT给出随机的打招呼文字。',
component: 'Input'
}
],
// 获取配置数据方法(用于前端填充显示数据)
@ -472,7 +42,22 @@ export function supportGuoba () {
for (let [keyPath, value] of Object.entries(data)) {
// 处理黑名单
if (keyPath === 'blockWords' || keyPath === 'promptBlockWords' || keyPath === 'initiativeChatGroups') { value = value.toString().split(/[,;\|]/) }
if (Config[keyPath] != value) { Config[keyPath] = value }
if (keyPath === 'blacklist' || keyPath === 'whitelist') {
// 6-10位数的群号或qq
const regex = /^\^?[1-9]\d{5,9}(\^[1-9]\d{5,9})?$/
const inputSet = new Set()
value = value.toString().split(/[,;|\s]/).reduce((acc, item) => {
item = item.trim()
if (!inputSet.has(item) && regex.test(item)) {
if (item.length <= 11 || (item.length <= 21 && item.length > 11 && !item.startsWith('^'))) {
inputSet.add(item)
acc.push(item)
}
}
return acc
}, [])
}
if (Config[keyPath] !== value) { Config[keyPath] = value }
}
return Result.ok({}, '保存成功~')
}

View file

@ -1,5 +1,16 @@
import fs from 'node:fs'
import {Config} from "./utils/config.js";
import ChatGPTConfig from './config/config.js'
import { initChaite } from './models/chaite/cloud.js'
logger.info('**************************************')
logger.info('chatgpt-plugin加载中')
if (!global.segment) {
try {
global.segment = (await import('icqq')).segment
} catch (err) {
global.segment = (await import('oicq')).segment
}
}
const files = fs.readdirSync('./plugins/chatgpt-plugin/apps').filter(file => file.endsWith('.js'))
@ -14,7 +25,6 @@ ret = await Promise.allSettled(ret)
let apps = {}
for (let i in files) {
let name = files[i].replace('.js', '')
if (ret[i].status !== 'fulfilled') {
logger.error(`载入插件错误:${logger.red(name)}`)
logger.error(ret[i].reason)
@ -22,10 +32,17 @@ for (let i in files) {
}
apps[name] = ret[i].value[Object.keys(ret[i].value)[0]]
}
logger.info('**************************************')
global.chatgpt = {
}
ChatGPTConfig.startSync('./plugins/chatgpt-plugin/data')
initChaite()
logger.info('chatgpt-plugin加载成功')
logger.info(`当前版本${Config.version}`)
logger.info(`当前版本${ChatGPTConfig.version}`)
logger.info('仓库地址 https://github.com/ikechan8370/chatgpt-plugin')
logger.info('文档地址 https://www.yunzai.chat')
logger.info('插件群号 559567232')
logger.info('**************************************')
export { apps }

207
models/chaite/cloud.js Normal file
View file

@ -0,0 +1,207 @@
import {
Chaite,
ChannelsManager,
ChatPresetManager,
DefaultChannelLoadBalancer,
ProcessorsManager,
RAGManager,
ToolManager,
ToolsGroupManager,
TriggerManager
} from 'chaite'
import ChatGPTConfig from '../../config/config.js'
import { LowDBChannelStorage } from './storage/lowdb/channel_storage.js'
import { LowDBChatPresetsStorage } from './storage/lowdb/chat_preset_storage.js'
import { LowDBToolsStorage } from './storage/lowdb/tools_storage.js'
import { LowDBProcessorsStorage } from './storage/lowdb/processors_storage.js'
import { ChatGPTUserModeSelector } from './user_mode_selector.js'
import { LowDBUserStateStorage } from './storage/lowdb/user_state_storage.js'
import { LowDBHistoryManager } from './storage/lowdb/history_manager.js'
import { VectraVectorDatabase } from './vector_database.js'
import path from 'path'
import fs from 'fs'
import { migrateDatabase } from '../../utils/initDB.js'
import { SQLiteChannelStorage } from './storage/sqlite/channel_storage.js'
import { dataDir } from '../../utils/common.js'
import { SQLiteChatPresetStorage } from './storage/sqlite/chat_preset_storage.js'
import { SQLiteToolsStorage } from './storage/sqlite/tools_storage.js'
import { SQLiteProcessorsStorage } from './storage/sqlite/processors_storage.js'
import { SQLiteUserStateStorage } from './storage/sqlite/user_state_storage.js'
import { SQLiteToolsGroupStorage } from './storage/sqlite/tool_groups_storage.js'
import { checkMigrate } from './storage/sqlite/migrate.js'
import { SQLiteHistoryManager } from './storage/sqlite/history_manager.js'
import SQLiteTriggerStorage from './storage/sqlite/trigger_storage.js'
import LowDBTriggerStorage from './storage/lowdb/trigger_storage,.js'
import { createChaiteVectorizer } from './vectorizer.js'
import { MemoryRouter, authenticateMemoryRequest } from '../memory/router.js'
/**
* 认证以便共享上传
* @param apiKey
* @returns {Promise<import('chaite').User | null>}
*/
export async function authCloud (apiKey = ChatGPTConfig.chaite.cloudApiKey) {
try {
await Chaite.getInstance().auth(apiKey)
return Chaite.getInstance().getToolsManager().cloudService.getUser()
} catch (err) {
logger.error(err)
return null
}
}
/**
* 初始化RAG管理器
* @param {string} model
* @param {number} dimensions
*/
export async function initRagManager (model, dimensions) {
const vectorizer = createChaiteVectorizer(model, dimensions)
const vectorDBPath = path.resolve('./plugins/chatgpt-plugin', ChatGPTConfig.chaite.dataDir, 'vector_index')
if (!fs.existsSync(vectorDBPath)) {
fs.mkdirSync(vectorDBPath, { recursive: true })
}
const vectorDB = new VectraVectorDatabase(vectorDBPath)
await vectorDB.init()
const ragManager = new RAGManager(vectorDB, vectorizer)
return Chaite.getInstance().setRAGManager(ragManager)
}
export async function initChaite () {
const storage = ChatGPTConfig.chaite.storage
let channelsStorage, chatPresetsStorage, toolsStorage, processorsStorage, userStateStorage, historyStorage, toolsGroupStorage, triggerStorage
switch (storage) {
case 'sqlite': {
const dbPath = path.join(dataDir, 'data.db')
channelsStorage = new SQLiteChannelStorage(dbPath)
await channelsStorage.initialize()
chatPresetsStorage = new SQLiteChatPresetStorage(dbPath)
await chatPresetsStorage.initialize()
toolsStorage = new SQLiteToolsStorage(dbPath)
await toolsStorage.initialize()
processorsStorage = new SQLiteProcessorsStorage(dbPath)
await processorsStorage.initialize()
userStateStorage = new SQLiteUserStateStorage(dbPath)
await userStateStorage.initialize()
toolsGroupStorage = new SQLiteToolsGroupStorage(dbPath)
await toolsGroupStorage.initialize()
triggerStorage = new SQLiteTriggerStorage(dbPath)
await triggerStorage.initialize()
historyStorage = new SQLiteHistoryManager(dbPath, path.join(dataDir, 'images'))
await checkMigrate()
break
}
case 'lowdb': {
const ChatGPTStorage = (await import('storage/lowdb/storage.js')).default
await ChatGPTStorage.init()
channelsStorage = new LowDBChannelStorage(ChatGPTStorage)
chatPresetsStorage = new LowDBChatPresetsStorage(ChatGPTStorage)
toolsStorage = new LowDBToolsStorage(ChatGPTStorage)
processorsStorage = new LowDBProcessorsStorage(ChatGPTStorage)
userStateStorage = new LowDBUserStateStorage(ChatGPTStorage)
triggerStorage = new LowDBTriggerStorage(ChatGPTStorage)
const ChatGPTHistoryStorage = (await import('storage/lowdb/storage.js')).ChatGPTHistoryStorage
await ChatGPTHistoryStorage.init()
historyStorage = new LowDBHistoryManager(ChatGPTHistoryStorage)
break
}
}
const channelsManager = await ChannelsManager.init(channelsStorage, new DefaultChannelLoadBalancer())
const toolsDir = path.resolve('./plugins/chatgpt-plugin', ChatGPTConfig.chaite.toolsDirPath)
if (!fs.existsSync(toolsDir)) {
fs.mkdirSync(toolsDir, { recursive: true })
}
const toolsManager = await ToolManager.init(toolsDir, toolsStorage)
const processorsDir = path.resolve('./plugins/chatgpt-plugin', ChatGPTConfig.chaite.processorsDirPath)
if (!fs.existsSync(processorsDir)) {
fs.mkdirSync(processorsDir, { recursive: true })
}
const processorsManager = await ProcessorsManager.init(processorsDir, processorsStorage)
const chatPresetManager = await ChatPresetManager.init(chatPresetsStorage)
const toolsGroupManager = await ToolsGroupManager.init(toolsGroupStorage)
const triggersDir = path.resolve('./plugins/chatgpt-plugin', ChatGPTConfig.chaite.triggersDir)
if (!fs.existsSync(triggersDir)) {
fs.mkdirSync(triggersDir, { recursive: true })
}
const triggerManager = new TriggerManager(triggersDir, triggerStorage)
await triggerManager.initialize()
const userModeSelector = new ChatGPTUserModeSelector()
let chaite = Chaite.init(channelsManager, toolsManager, processorsManager, chatPresetManager, toolsGroupManager, triggerManager,
userModeSelector, userStateStorage, historyStorage, logger)
logger.info('Chaite 初始化完成')
chaite.setCloudService(ChatGPTConfig.chaite.cloudBaseUrl)
logger.info('Chaite.Cloud 初始化完成')
await migrateDatabase()
if (ChatGPTConfig.chaite.cloudApiKey) {
const user = await authCloud(ChatGPTConfig.chaite.cloudApiKey)
if (user) {
logger.info(`Chaite.Cloud 认证成功, 当前用户${user.username || user.email} (${user.user_id})`)
} else {
logger.warn('Chaite.Cloud 认证失败,将继续使用本地功能')
}
}
await initRagManager(ChatGPTConfig.llm.embeddingModel, ChatGPTConfig.llm.dimensions)
if (!ChatGPTConfig.chaite.authKey) {
ChatGPTConfig.chaite.authKey = Chaite.getInstance().getFrontendAuthHandler().generateToken(0, true)
}
chaite.getGlobalConfig().setAuthKey(ChatGPTConfig.chaite.authKey)
// 监听Chaite配置变化同步需要同步的配置
chaite.on('config-change', obj => {
const { key, newVal, oldVal } = obj
if (key === 'authKey') {
ChatGPTConfig.serverAuthKey = newVal
}
logger.debug(`Chaite config changed: ${key} from ${oldVal} to ${newVal}`)
})
// 监听通过chaite对插件配置修改
chaite.setUpdateConfigCallback(config => {
logger.debug('chatgpt-plugin config updated')
// 设置保存来源标记,而不是使用 _isSaving
ChatGPTConfig._saveOrigin = 'chaite'
try {
Object.keys(config).forEach(key => {
if (typeof config[key] === 'object' && config[key] !== null && ChatGPTConfig[key]) {
deepMerge(ChatGPTConfig[key], config[key])
} else {
ChatGPTConfig[key] = config[key]
}
})
// 回传部分需要同步的配置
chaite.getGlobalConfig().setDebug(ChatGPTConfig.basic.debug)
chaite.getGlobalConfig().setAuthKey(ChatGPTConfig.chaite.authKey)
// 使用新的触发保存方法而不是直接调用saveToFile
ChatGPTConfig._triggerSave('chaite')
} finally {
// 不需要在这里清除标记_triggerSave已经处理了延迟清除
}
})
// 授予Chaite获取插件配置的能力以便通过api放出
chaite.setGetConfig(async () => {
return ChatGPTConfig
})
chaite.getGlobalConfig().setHost(ChatGPTConfig.chaite.host)
chaite.getGlobalConfig().setPort(ChatGPTConfig.chaite.port)
chaite.getGlobalConfig().setDebug(ChatGPTConfig.basic.debug)
logger.info('Chaite.RAGManager 初始化完成')
chaite.runApiServer(app => {
app.use('/api/memory', authenticateMemoryRequest, MemoryRouter)
})
}
function deepMerge (target, source) {
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (typeof source[key] === 'object' && source[key] !== null && target[key]) {
// 如果是对象且目标属性存在,递归合并
deepMerge(target[key], source[key])
} else {
// 否则直接赋值
target[key] = source[key]
}
}
}
}

View file

@ -0,0 +1,104 @@
import { ChaiteStorage, Channel } from 'chaite'
export class LowDBChannelStorage extends ChaiteStorage {
/**
*
* @param { LowDBStorage } storage
*/
constructor (storage) {
super()
this.storage = storage
/**
* 集合
* @type {LowDBCollection}
*/
this.collection = this.storage.collection('channel')
}
/**
*
* @param {string} key
* @returns {Promise<import('chaite').Channel>}
*/
async getItem (key) {
const obj = await this.collection.findOne({ id: key })
if (!obj) {
return null
}
return new Channel(obj)
}
/**
*
* @param {string} id
* @param {import('chaite').Channel} channel
* @returns {Promise<string>}
*/
async setItem (id, channel) {
if (id && await this.getItem(id)) {
await this.collection.updateById(id, channel)
return id
}
const result = await this.collection.insert(channel)
return result.id
}
/**
*
* @param {string} key
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.collection.deleteById(key)
}
/**
*
* @returns {Promise<import('chaite').Channel[]>}
*/
async listItems () {
const list = await this.collection.findAll()
return list.map(item => new Channel({}).fromString(JSON.stringify(item)))
}
/**
*
* @param {Record<string, unknown>} filter
* @returns {Promise<import('chaite').Channel[]>}
*/
async listItemsByEqFilter (filter) {
const allList = await this.listItems()
return allList.filter(item => {
for (const key in filter) {
if (item[key] !== filter[key]) {
return false
}
}
return true
})
}
/**
*
* @param {Array<{
* field: string;
* values: unknown[];
* }>} query
* @returns {Promise<import('chaite').Channel[]>}
*/
async listItemsByInQuery (query) {
const allList = await this.listItems()
return allList.filter(item => {
for (const { field, values } of query) {
if (!values.includes(item[field])) {
return false
}
}
return true
})
}
async clear () {
await this.collection.deleteAll()
}
}

View file

@ -0,0 +1,107 @@
import { ChaiteStorage, ChatPreset } from 'chaite'
/**
* @extends {ChaiteStorage<import('chaite').ChatPreset>}
*/
export class LowDBChatPresetsStorage extends ChaiteStorage {
/**
*
* @param { LowDBStorage } storage
*/
constructor (storage) {
super()
this.storage = storage
/**
* 集合
* @type {LowDBCollection}
*/
this.collection = this.storage.collection('chat_presets')
}
/**
*
* @param key
* @returns {Promise<import('chaite').ChatPreset>}
*/
async getItem (key) {
const obj = await this.collection.findOne({ id: key })
if (!obj) {
return null
}
return new ChatPreset(obj)
}
/**
*
* @param {string} id
* @param {import('chaite').ChatPreset} preset
* @returns {Promise<string>}
*/
async setItem (id, preset) {
if (id && await this.getItem(id)) {
await this.collection.updateById(id, preset)
return id
}
const result = await this.collection.insert(preset)
return result.id
}
/**
*
* @param {string} key
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.collection.deleteById(key)
}
/**
*
* @returns {Promise<import('chaite').ChatPreset[]>}
*/
async listItems () {
const list = await this.collection.findAll()
return list.map(item => new ChatPreset({}).fromString(JSON.stringify(item)))
}
/**
*
* @param {Record<string, unknown>} filter
* @returns {Promise<import('chaite').ChatPreset[]>}
*/
async listItemsByEqFilter (filter) {
const allList = await this.listItems()
return allList.filter(item => {
for (const key in filter) {
if (item[key] !== filter[key]) {
return false
}
}
return true
})
}
/**
*
* @param {Array<{
* field: string;
* values: unknown[];
* }>} query
* @returns {Promise<import('chaite').ChatPreset[]>}
*/
async listItemsByInQuery (query) {
const allList = await this.listItems()
return allList.filter(item => {
for (const { field, values } of query) {
if (!values.includes(item[field])) {
return false
}
}
return true
})
}
async clear () {
await this.collection.deleteAll()
}
}

View file

@ -0,0 +1,56 @@
import { AbstractHistoryManager } from 'chaite'
export class LowDBHistoryManager extends AbstractHistoryManager {
/**
*
* @param { LowDBStorage } storage
*/
constructor (storage) {
super()
this.storage = storage
/**
* 集合
* @type {LowDBCollection}
*/
this.collection = this.storage.collection('history')
}
async saveHistory (message, conversationId) {
const historyObj = { ...message, conversationId }
if (message.id) {
await this.collection.updateById(message.id, historyObj)
}
await this.collection.insert(historyObj)
}
/**
*
* @param messageId
* @param conversationId
* @returns {Promise<import('chaite').HistoryMessage[]>}
*/
async getHistory (messageId, conversationId) {
if (messageId) {
const messages = []
let currentId = messageId
while (currentId) {
const message = await this.collection.findOne({ id: currentId })
if (!message) break
messages.unshift(message)
currentId = message.parentId
}
return messages
} else if (conversationId) {
return this.collection.find({ conversationId })
}
return []
}
async deleteConversation (conversationId) {
await this.collection.delete({ conversationId })
}
async getOneHistory (messageId, conversationId) {
return this.collection.findOne({ id: messageId, conversationId })
}
}

View file

@ -0,0 +1,107 @@
import { ChaiteStorage, ProcessorDTO } from 'chaite'
/**
* @extends {ChaiteStorage<import('chaite').Processor>}
*/
export class LowDBProcessorsStorage extends ChaiteStorage {
/**
*
* @param { LowDBStorage } storage
*/
constructor (storage) {
super()
this.storage = storage
/**
* 集合
* @type {LowDBCollection}
*/
this.collection = this.storage.collection('processors')
}
/**
*
* @param {string} key
* @returns {Promise<import('chaite').Processor>}
*/
async getItem (key) {
const obj = await this.collection.findOne({ id: key })
if (!obj) {
return null
}
return new ProcessorDTO(obj)
}
/**
*
* @param {string} id
* @param {import('chaite').Processor} processor
* @returns {Promise<string>}
*/
async setItem (id, processor) {
if (id && await this.getItem(id)) {
await this.collection.updateById(id, processor)
return id
}
const result = await this.collection.insert(processor)
return result.id
}
/**
*
* @param {string} key
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.collection.deleteById(key)
}
/**
*
* @returns {Promise<import('chaite').Processor[]>}
*/
async listItems () {
const list = await this.collection.findAll()
return list.map(item => new ProcessorDTO({}).fromString(JSON.stringify(item)))
}
/**
*
* @param {Record<string, unknown>} filter
* @returns {Promise<import('chaite').Processor[]>}
*/
async listItemsByEqFilter (filter) {
const allList = await this.listItems()
return allList.filter(item => {
for (const key in filter) {
if (item[key] !== filter[key]) {
return false
}
}
return true
})
}
/**
*
* @param {Array<{
* field: string;
* values: unknown[];
* }>} query
* @returns {Promise<import('chaite').Processor[]>}
*/
async listItemsByInQuery (query) {
const allList = await this.listItems()
return allList.filter(item => {
for (const { field, values } of query) {
if (!values.includes(item[field])) {
return false
}
}
return true
})
}
async clear () {
await this.collection.deleteAll()
}
}

View file

@ -0,0 +1,374 @@
// storage.js written by sonnet
import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'
import path from 'path'
import fs from 'fs'
import { dataDir } from '../../../../utils/common.js'
/**
* 基于 LowDB 的简单存储类提供 CRUD 和条件查询功能
*/
export class LowDBStorage {
/**
* 创建一个新的存储实例
* @param {Object} options 配置选项
* @param {string} options.filename 数据文件名称
* @param {string} options.directory 数据目录默认为当前目录下的 data 文件夹
*/
constructor (options = {}) {
const { filename = 'db.json', directory = path.join(process.cwd(), 'data') } = options
// 确保目录存在
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory, { recursive: true })
}
this.filePath = path.join(directory, filename)
this.adapter = new JSONFile(this.filePath)
this.db = new Low(this.adapter, { collections: {} })
this.initialized = false
}
/**
* 初始化存储
* @returns {Promise<LowDBStorage>} 当前存储实例
*/
async init () {
// 读取数据文件,如果不存在则创建默认结构
await this.db.read()
this.db.data ||= { collections: {} }
await this.db.write()
this.initialized = true
return this
}
/**
* 获取或创建一个集合
* @param {string} name 集合名称
* @returns {LowDBCollection} 集合实例
*/
collection (name) {
this._checkInit()
// 确保集合存在
if (!this.db.data.collections[name]) {
this.db.data.collections[name] = []
this.db.write()
}
return new LowDBCollection(this, name)
}
/**
* 列出所有集合名称
* @returns {string[]} 集合名称列表
*/
listCollections () {
this._checkInit()
return Object.keys(this.db.data.collections)
}
/**
* 删除一个集合
* @param {string} name 要删除的集合名称
* @returns {Promise<boolean>} 是否成功删除
*/
async dropCollection (name) {
this._checkInit()
if (this.db.data.collections[name]) {
delete this.db.data.collections[name]
await this.db.write()
return true
}
return false
}
/**
* 检查存储是否已初始化
* @private
*/
_checkInit () {
if (!this.initialized) {
throw new Error('存储尚未初始化,请先调用 init() 方法')
}
}
}
/**
* 集合类提供对特定数据集合的操作
*/
export class LowDBCollection {
/**
* 创建一个集合实例
* @param {LowDBStorage} storage 所属存储实例
* @param {string} name 集合名称
*/
constructor (storage, name) {
this.storage = storage
this.name = name
}
/**
* 获取集合数据引用
* @private
*/
get _collection () {
return this.storage.db.data.collections[this.name]
}
/**
* 保存数据到存储
* @private
*/
async _save () {
return this.storage.db.write()
}
/**
* 生成唯一ID
* @private
*/
_generateId () {
return Date.now().toString(36) + Math.random().toString(36).substring(2, 15)
}
/**
* 创建新文档
* @param {Object} doc 要插入的文档
* @returns {Promise<Object & {id: string}>} 插入的文档带ID
*/
async insert (doc) {
// 生成唯一ID如果没有提供
if (!doc.id) {
doc.id = this._generateId()
}
// 加上时间戳
if (!doc.createdAt) {
doc.createdAt = new Date().toISOString()
}
doc.updatedAt = new Date().toISOString()
// 添加到集合
this._collection.push(doc)
await this._save()
return doc
}
/**
* 批量插入多个文档
* @param {Object[]} docs 要插入的文档数组
* @returns {Promise<Object[]>} 插入的文档带ID
*/
async insertMany (docs) {
const inserted = []
for (const doc of docs) {
inserted.push(await this.insert(doc))
}
return inserted
}
/**
* 根据ID查找单个文档
* @param {string} id 文档ID
* @returns {Promise<Object|null>} 查找到的文档或null
*/
async findById (id) {
return this._collection.find(doc => doc.id === id) || null
}
/**
* 返回集合中的所有文档
* @returns {Promise<Object[]>} 文档数组
*/
async findAll () {
return [...this._collection]
}
/**
* 根据条件查找文档
* @param {Object} query 查询条件字段等值匹配
* @returns {Promise<Object[]>} 匹配的文档数组
*/
async find (query = {}) {
return this._collection.filter(doc => {
for (const key in query) {
const value = query[key]
// 处理嵌套属性 (例如 user.profile.name)
if (key.includes('.')) {
const parts = key.split('.')
let current = doc
for (let i = 0; i < parts.length; i++) {
if (current === undefined || current === null) return false
current = current[parts[i]]
}
if (current !== value) return false
} else if (doc[key] !== value) {
return false
}
}
return true
})
}
/**
* 根据条件查找单个文档
* @param {Object} query 查询条件
* @returns {Promise<Object|null>} 第一个匹配的文档或null
*/
async findOne (query = {}) {
const results = await this.find(query)
return results.length > 0 ? results[0] : null
}
/**
* 使用自定义函数进行高级查询
* @param {Function} filterFn 过滤函数
* @returns {Promise<Object[]>} 匹配的文档数组
*/
async findWhere (filterFn) {
return this._collection.filter(filterFn)
}
/**
* 根据ID更新文档
* @param {string} id 文档ID
* @param {Object} updates 要更新的字段
* @returns {Promise<Object|null>} 更新后的文档或null
*/
async updateById (id, updates) {
const index = this._collection.findIndex(doc => doc.id === id)
if (index === -1) return null
// 防止覆盖ID
const { id: _, ...safeUpdates } = updates
// 更新文档
const updatedDoc = {
...this._collection[index],
...safeUpdates,
updatedAt: new Date().toISOString()
}
this._collection[index] = updatedDoc
await this._save()
return updatedDoc
}
/**
* 根据条件更新文档
* @param {Object} query 查询条件
* @param {Object} updates 要更新的字段
* @returns {Promise<number>} 更新的文档数量
*/
async update (query, updates) {
const matches = await this.find(query)
let updated = 0
for (const doc of matches) {
await this.updateById(doc.id, updates)
updated++
}
return updated
}
/**
* 根据ID删除文档
* @param {string} id 文档ID
* @returns {Promise<boolean>} 是否成功删除
*/
async deleteById (id) {
const index = this._collection.findIndex(doc => doc.id === id)
if (index === -1) return false
this._collection.splice(index, 1)
await this._save()
return true
}
/**
* 根据条件删除文档
* @param {Object} query 查询条件
* @returns {Promise<number>} 删除的文档数量
*/
async delete (query) {
const before = this._collection.length
const remaining = this._collection.filter(doc => {
for (const key in query) {
if (doc[key] !== query[key]) {
return true // 保留不匹配的
}
}
return false // 删除匹配的
})
this.storage.db.data.collections[this.name] = remaining
await this._save()
return before - remaining.length
}
/**
* 清空集合中的所有文档
* @returns {Promise<number>} 删除的文档数量
*/
async deleteAll () {
const count = this._collection.length
this.storage.db.data.collections[this.name] = []
await this._save()
return count
}
/**
* 返回集合中文档的数量
* @returns {Promise<number>} 文档数量
*/
async count (query = {}) {
if (Object.keys(query).length === 0) {
return this._collection.length
}
const matches = await this.find(query)
return matches.length
}
}
const storageLocation = path.resolve(dataDir, 'storage.json')
if (!fs.existsSync(storageLocation)) {
fs.writeFileSync(storageLocation, JSON.stringify({ collections: {} }))
}
const ChatGPTStorage = new LowDBStorage({
filename: 'storage.json',
directory: dataDir
})
if (ChatGPTStorage.db.data.collections.history) {
ChatGPTStorage.dropCollection('history').then(() => {
logger.debug('drop older version history collection')
}).catch(err => {
logger.warn('failed to drop older version history collection', err)
})
}
export const ChatGPTHistoryStorage = new LowDBStorage({
filename: 'history.json',
directory: dataDir
})
export default ChatGPTStorage

View file

@ -0,0 +1,70 @@
import { ChaiteStorage, ToolsGroupDTO } from 'chaite'
/**
* @extends {ChaiteStorage<import('chaite').ToolsGroupDTO>}
*/
export class LowDBToolsGroupDTOsStorage extends ChaiteStorage {
/**
*
* @param { LowDBStorage } storage
*/
constructor (storage) {
super()
this.storage = storage
/**
* 集合
* @type {LowDBCollection}
*/
this.collection = this.storage.collection('tool_groups')
}
/**
*
* @param key
* @returns {Promise<import('chaite').ToolsGroupDTO>}
*/
async getItem (key) {
const obj = await this.collection.findOne({ id: key })
if (!obj) {
return null
}
return new ToolsGroupDTO(obj)
}
/**
*
* @param {string} id
* @param {import('chaite').ToolsGroupDTO} preset
* @returns {Promise<string>}
*/
async setItem (id, preset) {
if (id && await this.getItem(id)) {
await this.collection.updateById(id, preset)
return id
}
const result = await this.collection.insert(preset)
return result.id
}
/**
*
* @param {string} key
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.collection.deleteById(key)
}
/**
*
* @returns {Promise<import('chaite').ToolsGroupDTO[]>}
*/
async listItems () {
const list = await this.collection.findAll()
return list.map(item => new ToolsGroupDTO({}).fromString(JSON.stringify(item)))
}
async clear () {
await this.collection.deleteAll()
}
}

View file

@ -0,0 +1,111 @@
import { ChaiteStorage, ToolDTO } from 'chaite'
/**
* @extends {ChaiteStorage<import('chaite').ToolDTO>}
*/
export class LowDBToolsStorage extends ChaiteStorage {
getName () {
return 'LowDBToolsStorage'
}
/**
*
* @param { LowDBStorage } storage
*/
constructor (storage) {
super()
this.storage = storage
/**
* 集合
* @type {LowDBCollection}
*/
this.collection = this.storage.collection('tools')
}
/**
*
* @param {string} key
* @returns {Promise<import('chaite').ToolDTO>}
*/
async getItem (key) {
const obj = await this.collection.findOne({ id: key })
if (!obj) {
return null
}
return new ToolDTO(obj)
}
/**
*
* @param {string} id
* @param {import('chaite').ToolDTO} tools
* @returns {Promise<string>}
*/
async setItem (id, tools) {
if (id && await this.getItem(id)) {
await this.collection.updateById(id, tools)
return id
}
const result = await this.collection.insert(tools)
return result.id
}
/**
*
* @param {string} key
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.collection.deleteById(key)
}
/**
*
* @returns {Promise<import('chaite').ToolDTO[]>}
*/
async listItems () {
const list = await this.collection.findAll()
return list.map(item => new ToolDTO({}).fromString(JSON.stringify(item)))
}
/**
*
* @param {Record<string, unknown>} filter
* @returns {Promise<import('chaite').ToolDTO[]>}
*/
async listItemsByEqFilter (filter) {
const allList = await this.listItems()
return allList.filter(item => {
for (const key in filter) {
if (item[key] !== filter[key]) {
return false
}
}
return true
})
}
/**
*
* @param {Array<{
* field: string;
* values: unknown[];
* }>} query
* @returns {Promise<import('chaite').ToolDTO[]>}
*/
async listItemsByInQuery (query) {
const allList = await this.listItems()
return allList.filter(item => {
for (const { field, values } of query) {
if (!values.includes(item[field])) {
return false
}
}
return true
})
}
async clear () {
await this.collection.deleteAll()
}
}

View file

@ -0,0 +1,122 @@
import { ChaiteStorage, TriggerDTO } from 'chaite'
/**
* @extends {ChaiteStorage<import('chaite').TriggerDTO>}
*/
export class LowDBTriggerStorage extends ChaiteStorage {
getName () {
return 'LowDBTriggerStorage'
}
/**
* @param {LowDBStorage} storage
*/
constructor (storage) {
super()
this.storage = storage
/**
* 集合
* @type {LowDBCollection}
*/
this.collection = this.storage.collection('triggers')
}
/**
* 获取单个触发器
* @param {string} key
* @returns {Promise<import('chaite').TriggerDTO>}
*/
async getItem (key) {
const obj = await this.collection.findOne({ id: key })
if (!obj) {
return null
}
return new TriggerDTO(obj)
}
/**
* 保存触发器
* @param {string} id
* @param {import('chaite').TriggerDTO} trigger
* @returns {Promise<string>}
*/
async setItem (id, trigger) {
// 设置或更新时间戳
if (!trigger.createdAt) {
trigger.createdAt = new Date().toISOString()
}
trigger.updatedAt = new Date().toISOString()
if (id && await this.getItem(id)) {
await this.collection.updateById(id, trigger)
return id
}
const result = await this.collection.insert(trigger)
return result.id
}
/**
* 删除触发器
* @param {string} key
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.collection.deleteById(key)
}
/**
* 获取所有触发器
* @returns {Promise<import('chaite').TriggerDTO[]>}
*/
async listItems () {
const list = await this.collection.findAll()
return list.map(item => new TriggerDTO({}).fromString(JSON.stringify(item)))
}
/**
* 根据条件筛选触发器
* @param {Record<string, unknown>} filter
* @returns {Promise<import('chaite').TriggerDTO[]>}
*/
async listItemsByEqFilter (filter) {
const allList = await this.listItems()
return allList.filter(item => {
for (const key in filter) {
if (item[key] !== filter[key]) {
return false
}
}
return true
})
}
/**
* 根据IN条件筛选触发器
* @param {Array<{
* field: string;
* values: unknown[];
* }>} query
* @returns {Promise<import('chaite').TriggerDTO[]>}
*/
async listItemsByInQuery (query) {
const allList = await this.listItems()
return allList.filter(item => {
for (const { field, values } of query) {
if (!values.includes(item[field])) {
return false
}
}
return true
})
}
/**
* 清空所有触发器
* @returns {Promise<void>}
*/
async clear () {
await this.collection.deleteAll()
}
}
export default LowDBTriggerStorage

View file

@ -0,0 +1,84 @@
import { ChaiteStorage } from 'chaite'
import * as crypto from 'node:crypto'
/**
* 继承UserState
*/
export class YunzaiUserState {
constructor (userId, nickname, card, conversationId = crypto.randomUUID()) {
this.userId = userId
this.nickname = nickname
this.card = card
this.conversations = []
this.settings = {}
this.current = {
conversationId,
messageId: crypto.randomUUID()
}
}
}
/**
* @extends {ChaiteStorage<import('chaite').UserState>}
*/
export class LowDBUserStateStorage extends ChaiteStorage {
/**
*
* @param {LowDBStorage} storage
*/
constructor (storage) {
super()
this.storage = storage
/**
* 集合
* @type {LowDBCollection}
*/
this.collection = this.storage.collection('user_states')
}
/**
*
* @param {string} key
* @returns {Promise<import('chaite').UserState>}
*/
async getItem (key) {
return this.collection.findOne({ id: key })
}
/**
*
* @param {string} id
* @param {import('chaite').UserState} state
* @returns {Promise<string>}
*/
async setItem (id, state) {
if (id && await this.getItem(id)) {
await this.collection.updateById(id, state)
return id
}
state.id = id
const result = await this.collection.insert(state)
return result.id
}
/**
*
* @param {string} key
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.collection.deleteById(key)
}
/**
*
* @returns {Promise<import('chaite').UserState[]>}
*/
async listItems () {
return this.collection.findAll()
}
async clear () {
await this.collection.deleteAll()
}
}

View file

@ -0,0 +1,528 @@
import { ChaiteStorage, Channel } from 'chaite'
import sqlite3 from 'sqlite3'
import path from 'path'
import fs from 'fs'
import { generateId } from '../../../../utils/common.js'
/**
* @extends {ChaiteStorage<import('chaite').Channel>}
*/
export class SQLiteChannelStorage extends ChaiteStorage {
getName () {
return 'SQLiteChannelStorage'
}
/**
*
* @param {string} dbPath 数据库文件路径
*/
constructor (dbPath) {
super()
this.dbPath = dbPath
this.db = null
this.initialized = false
this.tableName = 'channels'
}
/**
* 初始化数据库连接和表结构
* @returns {Promise<void>}
*/
async initialize () {
if (this.initialized) return
return new Promise((resolve, reject) => {
// 确保目录存在
const dir = path.dirname(this.dbPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
this.db = new sqlite3.Database(this.dbPath, async (err) => {
if (err) {
return reject(err)
}
// 创建Channel表将主要属性分列存储
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
adapterType TEXT NOT NULL,
type TEXT NOT NULL,
weight INTEGER DEFAULT 1,
priority INTEGER DEFAULT 0,
status TEXT DEFAULT 'enabled',
disabledReason TEXT,
models TEXT,
options TEXT,
statistics TEXT,
uploader TEXT,
cloudId INTEGER,
createdAt TEXT,
updatedAt TEXT,
md5 TEXT,
embedded INTEGER DEFAULT 0,
extra TEXT -- 存储其他额外数据的JSON
)`, (err) => {
if (err) {
return reject(err)
}
// 创建索引提高查询性能
const promises = [
// 按类型和状态索引
new Promise((resolve, reject) => {
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_type ON ${this.tableName} (type)`, err => {
if (err) reject(err)
else resolve()
})
}),
new Promise((resolve, reject) => {
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_status ON ${this.tableName} (status)`, err => {
if (err) reject(err)
else resolve()
})
})
]
Promise.all(promises)
.then(() => {
this.initialized = true
resolve()
})
.catch(reject)
})
})
})
}
/**
* 确保数据库已初始化
*/
async ensureInitialized () {
if (!this.initialized) {
await this.initialize()
}
}
/**
* Channel 对象转换为数据库记录
* @param {import('chaite').Channel} channel
* @returns {Object} 数据库记录
*/
_channelToRecord (channel) {
// 提取主要字段
const {
id, name, description, adapterType, type, weight, priority,
status, disabledReason, models, options, statistics,
uploader, cloudId, createdAt, updatedAt, md5, embedded, ...rest
} = channel
return {
id: id || '',
name: name || '',
description: description || '',
adapterType: adapterType || type || '',
type: type || '',
weight: weight || 1,
priority: priority || 0,
status: status || 'enabled',
disabledReason: disabledReason || null,
models: Array.isArray(models) ? JSON.stringify(models) : '[]',
options: options ? JSON.stringify(options) : null,
statistics: statistics ? JSON.stringify(statistics) : null,
uploader: uploader ? JSON.stringify(uploader) : null,
cloudId: cloudId || null,
createdAt: createdAt || '',
updatedAt: updatedAt || '',
md5: md5 || '',
embedded: embedded ? 1 : 0,
extra: Object.keys(rest).length > 0 ? JSON.stringify(rest) : null
}
}
/**
* 将数据库记录转换为 Channel 对象
* @param {Object} record 数据库记录
* @returns {import('chaite').Channel} Channel 对象
*/
_recordToChannel (record) {
if (!record) return null
// 解析JSON字段
let models = []
try {
if (record.models) {
models = JSON.parse(record.models)
}
} catch (e) {
// 解析错误,使用空数组
}
let options = {}
try {
if (record.options) {
options = JSON.parse(record.options)
}
} catch (e) {
// 解析错误,使用空对象
}
let statistics = {}
try {
if (record.statistics) {
statistics = JSON.parse(record.statistics)
}
} catch (e) {
// 解析错误,使用空对象
}
let uploader = null
try {
if (record.uploader) {
uploader = JSON.parse(record.uploader)
}
} catch (e) {
// 解析错误使用null
}
let extra = {}
try {
if (record.extra) {
extra = JSON.parse(record.extra)
}
} catch (e) {
// 解析错误,使用空对象
}
// 构造Channel对象
const channelData = {
id: record.id,
name: record.name,
description: record.description,
adapterType: record.adapterType,
type: record.type,
weight: Number(record.weight),
priority: Number(record.priority),
status: record.status,
disabledReason: record.disabledReason,
models,
options,
statistics,
uploader,
cloudId: record.cloudId,
createdAt: record.createdAt,
updatedAt: record.updatedAt,
md5: record.md5,
embedded: Boolean(record.embedded),
...extra
}
return new Channel(channelData)
}
/**
* 获取单个渠道
* @param {string} key 渠道ID
* @returns {Promise<import('chaite').Channel>}
*/
async getItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
if (err) {
return reject(err)
}
const channel = this._recordToChannel(row)
resolve(channel)
})
})
}
/**
* 保存渠道
* @param {string} id 渠道ID
* @param {import('chaite').Channel} channel 渠道对象
* @returns {Promise<string>}
*/
async setItem (id, channel) {
await this.ensureInitialized()
if (!id) {
id = generateId()
}
// 加上时间戳
if (!channel.createdAt) {
channel.createdAt = new Date().toISOString()
}
channel.updatedAt = new Date().toISOString()
// 转换为数据库记录
const record = this._channelToRecord(channel)
record.id = id // 确保ID是指定的ID
// 构建插入或更新SQL
const fields = Object.keys(record)
const placeholders = fields.map(() => '?').join(', ')
const updates = fields.map(field => `${field} = ?`).join(', ')
const values = fields.map(field => record[field])
const duplicateValues = [...values] // 用于ON CONFLICT时的更新
return new Promise((resolve, reject) => {
this.db.run(
`INSERT INTO ${this.tableName} (${fields.join(', ')})
VALUES (${placeholders})
ON CONFLICT(id) DO UPDATE SET ${updates}`,
[...values, ...duplicateValues],
function (err) {
if (err) {
return reject(err)
}
resolve(id)
}
)
})
}
/**
* 删除渠道
* @param {string} key 渠道ID
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 查询所有渠道
* @returns {Promise<import('chaite').Channel[]>}
*/
async listItems () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
if (err) {
return reject(err)
}
const channels = rows.map(row => this._recordToChannel(row)).filter(Boolean)
resolve(channels)
})
})
}
/**
* 根据条件筛选渠道
* @param {Record<string, unknown>} filter 筛选条件
* @returns {Promise<import('chaite').Channel[]>}
*/
async listItemsByEqFilter (filter) {
await this.ensureInitialized()
// 如果没有筛选条件,返回所有
if (!filter || Object.keys(filter).length === 0) {
return this.listItems()
}
// 尝试使用SQL字段直接过滤
const directFields = ['id', 'name', 'description', 'adapterType', 'type', 'status', 'cloudId']
const numericFields = ['weight', 'priority']
const sqlFilters = []
const sqlParams = []
const extraFilters = {}
let hasExtraFilters = false
// 区分数据库字段和额外字段
for (const key in filter) {
const value = filter[key]
// 如果是直接支持的字段构建SQL条件
if (directFields.includes(key)) {
sqlFilters.push(`${key} = ?`)
sqlParams.push(value)
} else if (numericFields.includes(key)) {
// 数值型字段
sqlFilters.push(`${key} = ?`)
sqlParams.push(Number(value))
} else if (key === 'embedded') {
// embedded 字段需要特殊处理为 0/1
sqlFilters.push('embedded = ?')
sqlParams.push(value ? 1 : 0)
} else if (key === 'models' && typeof value === 'string') {
// models字段需要特殊处理判断是否包含某模型
// 注意:这种方式仅适用于单个模型的查询,不适用于完全匹配数组
sqlFilters.push('models LIKE ?')
sqlParams.push(`%${value}%`)
} else {
// 其他字段需要在结果中进一步过滤
extraFilters[key] = value
hasExtraFilters = true
}
}
// 构建SQL查询
let sql = `SELECT * FROM ${this.tableName}`
if (sqlFilters.length > 0) {
sql += ` WHERE ${sqlFilters.join(' AND ')}`
}
return new Promise((resolve, reject) => {
this.db.all(sql, sqlParams, (err, rows) => {
if (err) {
return reject(err)
}
let channels = rows.map(row => this._recordToChannel(row)).filter(Boolean)
// 如果有需要在内存中过滤的额外<E9A29D><E5A496><EFBFBD>
if (hasExtraFilters) {
channels = channels.filter(channel => {
for (const key in extraFilters) {
if (channel[key] !== extraFilters[key]) {
return false
}
}
return true
})
}
resolve(channels)
})
})
}
/**
* 根据IN条件筛选渠道
* @param {Array<{ field: string; values: unknown[]; }>} query
* @returns {Promise<import('chaite').Channel[]>}
*/
async listItemsByInQuery (query) {
await this.ensureInitialized()
// 如果没有查询条件,返回所有
if (!query || query.length === 0) {
return this.listItems()
}
// 尝试使用SQL IN子句来优化查询
const directFields = ['id', 'name', 'description', 'adapterType', 'type', 'status', 'cloudId']
const numericFields = ['weight', 'priority']
const sqlFilters = []
const sqlParams = []
const extraQueries = []
// 处理每个查询条件
for (const { field, values } of query) {
if (values.length === 0) continue
// 如果是直接支持的字段使用SQL IN子句
if (directFields.includes(field)) {
const placeholders = values.map(() => '?').join(', ')
sqlFilters.push(`${field} IN (${placeholders})`)
sqlParams.push(...values)
} else if (numericFields.includes(field)) {
// 数值型字段
const placeholders = values.map(() => '?').join(', ')
sqlFilters.push(`${field} IN (${placeholders})`)
sqlParams.push(...values.map(v => Number(v)))
} else if (field === 'embedded') {
// embedded 字段需要特殊处理
const boolValues = values.map(v => v ? 1 : 0)
const placeholders = boolValues.map(() => '?').join(', ')
sqlFilters.push(`embedded IN (${placeholders})`)
sqlParams.push(...boolValues)
} else if (field === 'models') {
// models字段需要特殊处理判断是否包含某模型
// 由于无法直接使用IN查询JSON字段这里使用OR和LIKE的组合
const modelFilters = values.map(() => 'models LIKE ?').join(' OR ')
sqlFilters.push(`(${modelFilters})`)
values.forEach(value => {
sqlParams.push(`%${value}%`)
})
} else {
// 其他字段在内存中过滤
extraQueries.push({ field, values })
}
}
// 构建SQL查询
let sql = `SELECT * FROM ${this.tableName}`
if (sqlFilters.length > 0) {
sql += ` WHERE ${sqlFilters.join(' AND ')}`
}
return new Promise((resolve, reject) => {
this.db.all(sql, sqlParams, (err, rows) => {
if (err) {
return reject(err)
}
let channels = rows.map(row => this._recordToChannel(row)).filter(Boolean)
// 如果有需要在内存中过滤的条件
if (extraQueries.length > 0) {
channels = channels.filter(channel => {
for (const { field, values } of extraQueries) {
if (!values.includes(channel[field])) {
return false
}
}
return true
})
}
resolve(channels)
})
})
}
/**
* 清空表中所有数据
* @returns {Promise<void>}
*/
async clear () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 关闭数据库连接
* @returns {Promise<void>}
*/
async close () {
if (!this.db) return Promise.resolve()
return new Promise((resolve, reject) => {
this.db.close(err => {
if (err) {
reject(err)
} else {
this.initialized = false
this.db = null
resolve()
}
})
})
}
}

View file

@ -0,0 +1,523 @@
import { ChaiteStorage, ChatPreset } from 'chaite'
import sqlite3 from 'sqlite3'
import path from 'path'
import fs from 'fs'
import { generateId } from '../../../../utils/common.js'
/**
* @extends {ChaiteStorage<import('chaite').ChatPreset>}
*/
export class SQLiteChatPresetStorage extends ChaiteStorage {
getName () {
return 'SQLiteChatPresetStorage'
}
/**
*
* @param {string} dbPath 数据库文件路径
*/
constructor (dbPath) {
super()
this.dbPath = dbPath
this.db = null
this.initialized = false
this.tableName = 'chat_presets'
}
/**
* 初始化数据库连接和表结构
* @returns {Promise<void>}
*/
async initialize () {
if (this.initialized) return
return new Promise((resolve, reject) => {
// 确保目录存在
const dir = path.dirname(this.dbPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
this.db = new sqlite3.Database(this.dbPath, async (err) => {
if (err) {
return reject(err)
}
// 创建 ChatPreset 表,将主要属性分列存储
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
prefix TEXT NOT NULL,
local INTEGER DEFAULT 1,
namespace TEXT,
sendMessageOption TEXT NOT NULL,
cloudId INTEGER,
createdAt TEXT,
updatedAt TEXT,
md5 TEXT,
embedded INTEGER DEFAULT 0,
uploader TEXT,
extraData TEXT
)`, (err) => {
if (err) {
return reject(err)
}
// 创建索引提高查询性能
const promises = [
new Promise((resolve, reject) => {
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_prefix ON ${this.tableName} (prefix)`, (err) => {
if (err) {
reject(err)
} else {
resolve()
}
})
}),
new Promise((resolve, reject) => {
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_name ON ${this.tableName} (name)`, (err) => {
if (err) {
reject(err)
} else {
resolve()
}
})
})
]
Promise.all(promises)
.then(() => {
this.initialized = true
resolve()
})
.catch(reject)
})
})
})
}
/**
* 确保<EFBFBD><EFBFBD><EFBFBD>据库已初始化
*/
async ensureInitialized () {
if (!this.initialized) {
await this.initialize()
}
}
/**
* ChatPreset 对象转换为数据库记录
* @param {import('chaite').ChatPreset} preset
* @returns {Object} 数据库记录
*/
_presetToRecord (preset) {
// 提取主要字段
const {
id, name, description, prefix, local, namespace,
sendMessageOption, cloudId, createdAt, updatedAt, md5,
embedded, uploader, ...rest
} = preset
return {
id: id || '',
name: name || '',
description: description || '',
prefix: prefix || '',
local: local === false ? 0 : 1,
namespace: namespace || null,
sendMessageOption: JSON.stringify(sendMessageOption || {}),
cloudId: cloudId || null,
createdAt: createdAt || '',
updatedAt: updatedAt || '',
md5: md5 || '',
embedded: embedded ? 1 : 0,
uploader: uploader ? JSON.stringify(uploader) : null,
extraData: Object.keys(rest).length > 0 ? JSON.stringify(rest) : null
}
}
/**
* 将数<EFBFBD><EFBFBD><EFBFBD>库记录转换为 ChatPreset 对象
* @param {Object} record 数据库记录
* @returns {import('chaite').ChatPreset} ChatPreset 对象
*/
_recordToPreset (record) {
if (!record) return null
// 解析 JSON 字<><E5AD97>
let sendMessageOption = {}
try {
if (record.sendMessageOption) {
sendMessageOption = JSON.parse(record.sendMessageOption)
}
} catch (e) {
// 解析错误,使用空对象
}
let uploader = null
try {
if (record.uploader) {
uploader = JSON.parse(record.uploader)
}
} catch (e) {
// 解析错误,使用 null
}
let extraData = {}
try {
if (record.extraData) {
extraData = JSON.parse(record.extraData)
}
} catch (e) {
// 解析错误,使用空对象
}
// 构造 ChatPreset 对象
const presetData = {
id: record.id,
name: record.name,
description: record.description,
prefix: record.prefix,
local: Boolean(record.local),
namespace: record.namespace,
sendMessageOption,
cloudId: record.cloudId,
createdAt: record.createdAt,
updatedAt: record.updatedAt,
md5: record.md5,
embedded: Boolean(record.embedded),
uploader,
...extraData
}
return new ChatPreset(presetData)
}
/**
* 获取单个聊天预设
* @param {string} key 预设ID
* @returns {Promise<import('chaite').ChatPreset>}
*/
async getItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
if (err) {
return reject(err)
}
const preset = this._recordToPreset(row)
resolve(preset)
})
})
}
/**
* 保存聊天预设
* @param {string} id 预设ID
* @param {import('chaite').ChatPreset} preset 预设对象
* @returns {Promise<string>}
*/
async setItem (id, preset) {
await this.ensureInitialized()
if (!id) {
id = generateId()
}
// 加上时间戳
if (!preset.createdAt) {
preset.createdAt = new Date().toISOString()
}
preset.updatedAt = new Date().toISOString()
// 转换为数据库记录
const record = this._presetToRecord(preset)
record.id = id // 确保ID是指定的ID
// 构建插入或更新SQL
const fields = Object.keys(record)
const placeholders = fields.map(() => '?').join(', ')
const updates = fields.map(field => `${field} = ?`).join(', ')
const values = fields.map(field => record[field])
const duplicateValues = [...values] // 用于ON CONFLICT时的更新
return new Promise((resolve, reject) => {
this.db.run(
`INSERT INTO ${this.tableName} (${fields.join(', ')})
VALUES (${placeholders})
ON CONFLICT(id) DO UPDATE SET ${updates}`,
[...values, ...duplicateValues],
function (err) {
if (err) {
return reject(err)
}
resolve(id)
}
)
})
}
/**
* 删除聊天预设
* @param {string} key 预设ID
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 查询所有聊天预设
* @returns {Promise<import('chaite').ChatPreset[]>}
*/
async listItems () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
if (err) {
return reject(err)
}
const presets = rows.map(row => this._recordToPreset(row)).filter(Boolean)
resolve(presets)
})
})
}
/**
* 根据条件筛选聊天预设
* @param {Record<string, unknown>} filter 筛选条件
* @returns {Promise<import('chaite').ChatPreset[]>}
*/
async listItemsByEqFilter (filter) {
await this.ensureInitialized()
// 如果没有筛选条件,返回所有
if (!filter || Object.keys(filter).length === 0) {
return this.listItems()
}
// 尝试使用SQL字段直接过滤
const directFields = ['id', 'name', 'description', 'prefix', 'namespace', 'cloudId']
const sqlFilters = []
const sqlParams = []
const extraFilters = {}
let hasExtraFilters = false
// 区分数据库字段和额外字段
for (const key in filter) {
const value = filter[key]
// 如果是直接支持的字段构建SQL条件
if (directFields.includes(key)) {
sqlFilters.push(`${key} = ?`)
sqlParams.push(value)
} else if (key === 'local') {
// local 字段需要特殊处理为 0/1
sqlFilters.push('local = ?')
sqlParams.push(value ? 1 : 0)
} else if (key === 'embedded') {
// embedded 字段需要特殊处理为 0/1
sqlFilters.push('embedded = ?')
sqlParams.push(value ? 1 : 0)
} else {
// 其他字段需要在结果中进一步过滤
extraFilters[key] = value
hasExtraFilters = true
}
}
// 构建SQL查询
let sql = `SELECT * FROM ${this.tableName}`
if (sqlFilters.length > 0) {
sql += ` WHERE ${sqlFilters.join(' AND ')}`
}
return new Promise((resolve, reject) => {
this.db.all(sql, sqlParams, (err, rows) => {
if (err) {
return reject(err)
}
let presets = rows.map(row => this._recordToPreset(row)).filter(Boolean)
// 如果有需要在内存中过滤的额外字段
if (hasExtraFilters) {
presets = presets.filter(preset => {
for (const key in extraFilters) {
const filterValue = extraFilters[key]
// 处理 sendMessageOption 字段的深层过滤
if (key.startsWith('sendMessageOption.')) {
const optionKey = key.split('.')[1]
if (preset.sendMessageOption && preset.sendMessageOption[optionKey] !== filterValue) {
return false
}
} else if (preset[key] !== filterValue) {
// 其他字段直接比较
return false
}
}
return true
})
}
resolve(presets)
})
})
}
/**
* 根据IN条件筛选聊天预设
* @param {Array<{ field: string; values: unknown[]; }>} query
* @returns {Promise<import('chaite').ChatPreset[]>}
*/
async listItemsByInQuery (query) {
await this.ensureInitialized()
// 如果没有查询条件,返回所有
if (!query || query.length === 0) {
return this.listItems()
}
// 尝试使用SQL IN子句来优化查询
const directFields = ['id', 'name', 'description', 'prefix', 'namespace', 'cloudId']
const sqlFilters = []
const sqlParams = []
const extraQueries = []
// 处理每个查询条件
for (const { field, values } of query) {
if (values.length === 0) continue
// 如果是直接支持的字段使用SQL IN子句
if (directFields.includes(field)) {
const placeholders = values.map(() => '?').join(', ')
sqlFilters.push(`${field} IN (${placeholders})`)
sqlParams.push(...values)
} else if (field === 'local') {
// local 字段需要特殊处理
const boolValues = values.map(v => v ? 1 : 0)
const placeholders = boolValues.map(() => '?').join(', ')
sqlFilters.push(`local IN (${placeholders})`)
sqlParams.push(...boolValues)
} else if (field === 'embedded') {
// embedded 字段需要特殊处理
const boolValues = values.map(v => v ? 1 : 0)
const placeholders = boolValues.map(() => '?').join(', ')
sqlFilters.push(`embedded IN (${placeholders})`)
sqlParams.push(...boolValues)
} else {
// 其他字段在内存中过滤
extraQueries.push({ field, values })
}
}
// 构建SQL查询
let sql = `SELECT * FROM ${this.tableName}`
if (sqlFilters.length > 0) {
sql += ` WHERE ${sqlFilters.join(' AND ')}`
}
return new Promise((resolve, reject) => {
this.db.all(sql, sqlParams, (err, rows) => {
if (err) {
return reject(err)
}
let presets = rows.map(row => this._recordToPreset(row)).filter(Boolean)
// 如果有需要在内存中过滤的条件
if (extraQueries.length > 0) {
presets = presets.filter(preset => {
for (const { field, values } of extraQueries) {
// 处<><E5A484><EFBFBD> sendMessageOption 字段的深层过滤
if (field.startsWith('sendMessageOption.')) {
const optionKey = field.split('.')[1]
const presetValue = preset.sendMessageOption?.[optionKey]
if (!values.includes(presetValue)) {
return false
}
} else if (!values.includes(preset[field])) {
// 其他字段直接比较
return false
}
}
return true
})
}
resolve(presets)
})
})
}
/**
* 根据前缀获取聊天预设
* @param {string} prefix 前缀
* @returns {Promise<import('chaite').ChatPreset | null>}
*/
async getPresetByPrefix (prefix) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.get(`SELECT * FROM ${this.tableName} WHERE prefix = ?`, [prefix], (err, row) => {
if (err) {
return reject(err)
}
const preset = this._recordToPreset(row)
resolve(preset)
})
})
}
/**
* 清空表中所有数据
* @returns {Promise<void>}
*/
async clear () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 关闭数据库连接
* @returns {Promise<void>}
*/
async close () {
if (!this.db) return Promise.resolve()
return new Promise((resolve, reject) => {
this.db.close(err => {
if (err) {
reject(err)
} else {
this.initialized = false
this.db = null
resolve()
}
})
})
}
}

View file

@ -0,0 +1,596 @@
import { AbstractHistoryManager } from 'chaite'
import sqlite3 from 'sqlite3'
import path from 'path'
import fs from 'fs'
import crypto from 'crypto'
export class SQLiteHistoryManager extends AbstractHistoryManager {
/**
*
* @param {string} dbPath 数据库文件路径
* @param {string} imagesDir 图片存储目录默认为数据库同级的 images 目录
*/
constructor (dbPath, imagesDir) {
super()
this.dbPath = dbPath
this.imagesDir = imagesDir || path.join(path.dirname(dbPath), 'images')
this.db = null
this.initialized = false
this.tableName = 'history'
}
/**
* 初始化数据库连接和表结构
* @returns {Promise<void>}
*/
async initialize () {
if (this.initialized) return
return new Promise((resolve, reject) => {
// 确保目录存在
const dir = path.dirname(this.dbPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
// 确保图片目录存在
if (!fs.existsSync(this.imagesDir)) {
fs.mkdirSync(this.imagesDir, { recursive: true })
}
this.db = new sqlite3.Database(this.dbPath, async (err) => {
if (err) {
return reject(err)
}
// 创建 history 表
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
id TEXT PRIMARY KEY,
parentId TEXT,
conversationId TEXT,
role TEXT,
messageData TEXT,
createdAt TEXT
)`, (err) => {
if (err) {
return reject(err)
}
// 创建索引,加速查询
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_conversation ON ${this.tableName} (conversationId)`, (err) => {
if (err) {
return reject(err)
}
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_parent ON ${this.tableName} (parentId)`, (err) => {
if (err) {
return reject(err)
}
this.initialized = true
resolve()
})
})
})
})
})
}
/**
* 确保数据库已初始化
*/
async ensureInitialized () {
if (!this.initialized) {
await this.initialize()
}
}
/**
* 计算文本的md5值
* @param {string} text
* @returns {string}
*/
_getMd5 (text) {
return crypto.createHash('md5').update(text).digest('hex')
}
/**
* 是否为base64编码的图片
* @param {string} str
* @returns {boolean}
*/
_isBase64Image (str) {
if (!str || typeof str !== 'string') {
return false
}
// 处理带前缀的 base64 格式
if (str.startsWith('data:image/')) {
return true
}
// 处理纯 base64 字符串
// base64 编码只会包含字母、数字、+、/,以及末尾可能有 = 或 == 用于填充
return /^[A-Za-z0-9+/]+={0,2}$/.test(str)
}
/**
* 从base64提取图片的mime类型或使用默认类型
* @param {string} base64
* @param {string} defaultMimeType 默认 MIME 类型
* @returns {string}
*/
_getMimeTypeFromBase64 (base64, defaultMimeType = 'image/jpeg') {
if (base64 && base64.startsWith('data:image/')) {
const match = base64.match(/^data:(image\/[a-zA-Z+]+);base64,/)
if (match) {
return match[1]
}
}
return defaultMimeType // 对于纯 base64 字符串,使用默认类型
}
/**
* 获取图片扩展名
* @param {string} mimeType
* @returns {string}
*/
_getExtensionFromMimeType (mimeType) {
const map = {
'image/jpeg': '.jpg',
'image/png': '.png',
'image/gif': '.gif',
'image/webp': '.webp',
'image/svg+xml': '.svg'
}
return map[mimeType] || '.png'
}
/**
* 处理消息中的图片内容将base64图片保存到本地文件
* @param {object} message
* @returns {object} 处理后的消息对象
*/
_processMessageImages (message) {
if (!message.content || !Array.isArray(message.content)) {
return message
}
// 深拷贝避免修改原对象
const processedMessage = JSON.parse(JSON.stringify(message))
processedMessage.content = processedMessage.content.map(item => {
if (item.type === 'image' && item.image) {
// 检查是否是base64图片数据
if (this._isBase64Image(item.image)) {
let base64Data = item.image
let mimeType = item.mimeType || 'image/jpeg' // 使用项目指定的 MIME 类型或默认值
// 如果是data:image格式提取纯base64部分
if (base64Data.startsWith('data:')) {
const parts = base64Data.split(',')
if (parts.length > 1) {
base64Data = parts[1]
// 更新 MIME 类型
mimeType = this._getMimeTypeFromBase64(item.image, mimeType)
}
}
try {
// 计算MD5
const md5 = this._getMd5(base64Data)
const ext = this._getExtensionFromMimeType(mimeType)
const filePath = path.join(this.imagesDir, `${md5}${ext}`)
// 如果文件不存在,则保存
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, Buffer.from(base64Data, 'base64'))
}
// 替换为引用格式: $image:md5:ext
item.image = `$image:${md5}:${ext}`
item._type = mimeType // 保存原始类型
} catch (error) {
console.error('保存图片失败:', error)
}
}
}
return item
})
return processedMessage
}
/**
* 恢复消息中的图片引用转换回base64
* @param {object} message
* @returns {object} 处理后的消息对象
*/
_restoreMessageImages (message) {
if (!message || !message.content || !Array.isArray(message.content)) {
return message
}
// 深拷贝避免修改原对象
const restoredMessage = JSON.parse(JSON.stringify(message))
// 标记是否需要添加[图片]文本
let needImageText = true
let hasRemovedImage = false
restoredMessage.content = restoredMessage.content.filter((item, index) => {
if (item.type === 'image' && item.image && typeof item.image === 'string') {
// 检查是否是图片引用格式
const match = item.image.match(/^\$image:([a-f0-9]+):(\.[a-z]+)$/)
if (match) {
// eslint-disable-next-line no-unused-vars
const [_, md5, ext] = match
const filePath = path.join(this.imagesDir, `${md5}${ext}`)
// 检查文件是否存在
if (fs.existsSync(filePath)) {
try {
// 读取文件并转换为base64
const imageBuffer = fs.readFileSync(filePath)
item.image = imageBuffer.toString('base64')
return true
} catch (error) {
console.error('读取图片文件失败:', filePath, error)
hasRemovedImage = true
return false
}
} else {
// 文件不存在删除这个image元素
hasRemovedImage = true
return false
}
}
}
if (item.type === 'text') {
needImageText = false
}
return true
})
// 如果移除了图片且没有文本内容,添加[图片]提示
if (hasRemovedImage) {
if (restoredMessage.content.length === 0) {
restoredMessage.content.push({
type: 'text',
text: '[图片]'
})
} else if (needImageText) {
// 查找第一个文本元素
const textIndex = restoredMessage.content.findIndex(item => item.type === 'text')
if (textIndex !== -1) {
restoredMessage.content[textIndex].text = `[图片] ${restoredMessage.content[textIndex].text}`
} else {
// 如果没有文本元素,添加一个
restoredMessage.content.unshift({
type: 'text',
text: '[图片]'
})
}
}
}
return restoredMessage
}
/**
* 将消息对象转换为数据库记录
* @param {import('chaite').HistoryMessage} message
* @param {string} conversationId
* @returns {Object} 数据库记录
*/
_messageToRecord (message, conversationId) {
// 处理图片将base64图片保存到本地文件
const processedMessage = this._processMessageImages(message)
// 将 content 和 toolCalls 等转为 JSON
const { id, parentId, role } = processedMessage
const messageData = JSON.stringify(processedMessage)
return {
id: id || '',
parentId: parentId || null,
conversationId: conversationId || '',
role: role || '',
messageData,
createdAt: new Date().toISOString()
}
}
/**
* 将数据库记录转换为消息对象
* @param {Object} record 数据库记录
* @returns {import('chaite').HistoryMessage} 消息对象
*/
_recordToMessage (record) {
if (!record) return null
try {
// 解析存储的消息数据
const message = JSON.parse(record.messageData)
// 恢复图片引用为base64
return this._restoreMessageImages(message)
} catch (e) {
// 解析失败,尝试构造最小结构
return {
id: record.id,
parentId: record.parentId,
role: record.role,
conversationId: record.conversationId,
content: []
}
}
}
/**
* 保存历史消息
* @param {import('chaite').HistoryMessage} message 消息对象
* @param {string} conversationId 会话ID
* @returns {Promise<void>}
*/
async saveHistory (message, conversationId) {
await this.ensureInitialized()
const record = this._messageToRecord(message, conversationId)
return new Promise((resolve, reject) => {
// 检查消息是否已存在
if (message.id) {
this.db.get(`SELECT id FROM ${this.tableName} WHERE id = ?`, [message.id], (err, row) => {
if (err) {
return reject(err)
}
if (row) {
// 消息已存在,更新
const fields = Object.keys(record)
const updates = fields.map(field => `${field} = ?`).join(', ')
const values = fields.map(field => record[field])
this.db.run(`UPDATE ${this.tableName} SET ${updates} WHERE id = ?`, [...values, message.id], (err) => {
if (err) {
return reject(err)
}
resolve()
})
} else {
// 消息不存在,插入
this._insertMessage(record, resolve, reject)
}
})
} else {
// 没有ID直接插入
this._insertMessage(record, resolve, reject)
}
})
}
/**
* 内部方法插入消息记录
* @private
*/
_insertMessage (record, resolve, reject) {
const fields = Object.keys(record)
const placeholders = fields.map(() => '?').join(', ')
const values = fields.map(field => record[field])
this.db.run(
`INSERT INTO ${this.tableName} (${fields.join(', ')}) VALUES (${placeholders})`,
values,
function (err) {
if (err) {
return reject(err)
}
resolve()
}
)
}
/**
* 获取历史消息
* @param {string} messageId 消息ID
* @param {string} conversationId 会话ID
* @returns {Promise<import('chaite').HistoryMessage[]>}
*/
async getHistory (messageId, conversationId) {
await this.ensureInitialized()
if (messageId) {
return this._getMessageChain(messageId)
} else if (conversationId) {
return this._getConversationMessages(conversationId)
}
return []
}
/**
* 获取消息链从指定消息追溯到根消息
* @private
*/
async _getMessageChain (messageId) {
return new Promise((resolve, reject) => {
const messages = []
const getMessageById = (id) => {
if (!id) {
resolve(messages)
return
}
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [id], (err, row) => {
if (err) {
return reject(err)
}
if (!row) {
resolve(messages)
return
}
const message = this._recordToMessage(row)
messages.unshift(message) // 将消息添加到数组开头
getMessageById(row.parentId) // 递归获取父消息
})
}
getMessageById(messageId)
})
}
/**
* 获取会话中的所有消息
* @private
*/
async _getConversationMessages (conversationId) {
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM ${this.tableName} WHERE conversationId = ? ORDER BY createdAt`, [conversationId], (err, rows) => {
if (err) {
return reject(err)
}
const messages = rows.map(row => this._recordToMessage(row)).filter(Boolean)
resolve(messages)
})
})
}
/**
* 删除会话
* @param {string} conversationId 会话ID
* @returns {Promise<void>}
*/
async deleteConversation (conversationId) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName} WHERE conversationId = ?`, [conversationId], (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 获取单条历史消息
* @param {string} messageId 消息ID
* @param {string} conversationId 会话ID
* @returns {Promise<import('chaite').HistoryMessage | null>}
*/
async getOneHistory (messageId, conversationId) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
const conditions = []
const params = []
if (messageId) {
conditions.push('id = ?')
params.push(messageId)
}
if (conversationId) {
conditions.push('conversationId = ?')
params.push(conversationId)
}
if (conditions.length === 0) {
return resolve(null)
}
const whereClause = conditions.join(' AND ')
this.db.get(`SELECT * FROM ${this.tableName} WHERE ${whereClause} LIMIT 1`, params, (err, row) => {
if (err) {
return reject(err)
}
resolve(this._recordToMessage(row))
})
})
}
/**
* 清理未引用的图片文件
* @returns {Promise<{deleted: number, total: number}>}
*/
async cleanupUnusedImages () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
// 获取所有消息数据
this.db.all(`SELECT messageData FROM ${this.tableName}`, async (err, rows) => {
if (err) {
return reject(err)
}
try {
// 从数据库中提取所有图片引用
const usedImageRefs = new Set()
rows.forEach(row => {
try {
const message = JSON.parse(row.messageData)
if (message.content && Array.isArray(message.content)) {
message.content.forEach(item => {
if (item.type === 'image' && typeof item.image === 'string') {
const match = item.image.match(/^\$image:([a-f0-9]+):(\.[a-z]+)$/)
if (match) {
usedImageRefs.add(`${match[1]}${match[2]}`)
}
}
})
}
} catch (e) {
// 忽略解析错误
}
})
// 获取图片目录中的所有文件
const files = fs.readdirSync(this.imagesDir)
// 删除未引用的图片
let deletedCount = 0
for (const file of files) {
if (!usedImageRefs.has(file)) {
fs.unlinkSync(path.join(this.imagesDir, file))
deletedCount++
}
}
resolve({
deleted: deletedCount,
total: files.length
})
} catch (error) {
reject(error)
}
})
})
}
/**
* 关闭数据库连接
* @returns {Promise<void>}
*/
async close () {
if (!this.db) return Promise.resolve()
return new Promise((resolve, reject) => {
this.db.close(err => {
if (err) {
reject(err)
} else {
this.initialized = false
this.db = null
resolve()
}
})
})
}
}

View file

@ -0,0 +1,192 @@
import path from 'path'
import { dataDir } from '../../../../utils/common.js'
import { SQLiteChannelStorage } from './channel_storage.js'
import { LowDBChannelStorage } from '../lowdb/channel_storage.js'
import { SQLiteChatPresetStorage } from './chat_preset_storage.js'
import { LowDBChatPresetsStorage } from '../lowdb/chat_preset_storage.js'
import { SQLiteToolsStorage } from './tools_storage.js'
import { LowDBToolsStorage } from '../lowdb/tools_storage.js'
import { SQLiteProcessorsStorage } from './processors_storage.js'
import { LowDBProcessorsStorage } from '../lowdb/processors_storage.js'
import { SQLiteUserStateStorage } from './user_state_storage.js'
import { LowDBUserStateStorage } from '../lowdb/user_state_storage.js'
import fs from 'fs'
export async function checkMigrate () {
logger.debug('检查是否需要从 LowDB 迁移数据到 SQLite...')
try {
// 导入所需的模块
const { default: ChatGPTStorage } = await import('../lowdb/storage.js')
await ChatGPTStorage.init()
const { ChatGPTHistoryStorage } = await import('../lowdb/storage.js')
await ChatGPTHistoryStorage.init()
const dbPath = path.join(dataDir, 'data.db')
// 删除所有id为空的行
logger.debug('开始修复id为空的数据行...')
const collectionsToClean = ['channel', 'chat_presets', 'tools', 'processors']
for (const collectionName of collectionsToClean) {
try {
const collection = ChatGPTStorage.collection(collectionName)
const allItems = await collection.findAll()
const invalidItems = allItems.filter(item => !item.id)
if (invalidItems.length > 0) {
logger.info(`${collectionName}中发现${invalidItems.length}条id为空的数据正在修复...`)
for (const item of invalidItems) {
// 生成一个新的唯一ID
const newId = `generated_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
// 更新时间戳
const now = new Date().toISOString()
// 更新项目
item.id = newId
item.createdAt = now
item.updatedAt = now
// 保存更新后的项目
await collection.set(newId, item)
// 移除旧的无ID项
await collection.remove(item)
}
logger.info(`已成功修复${collectionName}中的${invalidItems.length}条无效数据`)
} else {
logger.debug(`${collectionName}中没有发现id为空的数据`)
}
} catch (err) {
logger.error(`修复${collectionName}中id为空的数据时出错:`, err)
}
}
// 定义要检查的存储对
const storagePairs = [
{
name: '渠道',
lowdbStorageClass: LowDBChannelStorage,
sqliteStorageClass: SQLiteChannelStorage,
collection: 'channel'
},
{
name: '预设',
lowdbStorageClass: LowDBChatPresetsStorage,
sqliteStorageClass: SQLiteChatPresetStorage,
collection: 'chat_presets'
},
{
name: '工具',
lowdbStorageClass: LowDBToolsStorage,
sqliteStorageClass: SQLiteToolsStorage,
collection: 'tools'
},
{
name: '处理器',
lowdbStorageClass: LowDBProcessorsStorage,
sqliteStorageClass: SQLiteProcessorsStorage,
collection: 'processors'
},
{
name: '用户状态',
lowdbStorageClass: LowDBUserStateStorage,
sqliteStorageClass: SQLiteUserStateStorage,
collection: 'userState',
isSpecial: true
}
]
// 检查是否有任何数据需要迁移
const needMigrate = await Promise.all(storagePairs.map(async pair => {
if (pair.isSpecial) {
// 用户状态特殊处理
const collection = ChatGPTStorage.collection(pair.collection)
const items = await collection.findAll()
return items.length > 0
} else {
// 标准集合处理
const collection = ChatGPTStorage.collection(pair.collection)
const items = await collection.findAll()
return items.length > 0
}
})).then(results => results.some(result => result))
if (!needMigrate) {
logger.debug('LowDB 存储为空,无需迁移')
return
}
// 检查 SQLite 中是否已有数据
const testStorage = new SQLiteChannelStorage(dbPath)
await testStorage.initialize()
const channels = await testStorage.listItems()
if (channels.length > 0) {
logger.debug('SQLite 存储已有数据,跳过迁移')
await testStorage.close()
return
}
await testStorage.close()
logger.info('开始从 LowDB 迁移数据到 SQLite...')
// 迁移每种数据
for (const pair of storagePairs) {
const collection = ChatGPTStorage.collection(pair.collection)
const items = await collection.findAll()
if (items.length > 0) {
logger.info(`迁移${pair.name}数据...`)
// eslint-disable-next-line new-cap
const sqliteStorage = new pair.sqliteStorageClass(dbPath)
await sqliteStorage.initialize()
for (const item of items) {
await sqliteStorage.setItem(item.id, item)
}
logger.info(`迁移了 ${items.length}${pair.name}`)
await sqliteStorage.close()
}
}
// 迁移完成后,备份并清空 LowDB 数据
const backupDir = path.join(dataDir, 'backup')
if (!fs.existsSync(backupDir)) {
fs.mkdirSync(backupDir, { recursive: true })
}
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
// 备份并清空<E6B885><E7A9BA>数据
if (fs.existsSync(ChatGPTStorage.filePath)) {
fs.copyFileSync(
ChatGPTStorage.filePath,
path.join(backupDir, `storage-backup-${timestamp}.json`)
)
// 清空数据但保留文件结构
for (const pair of storagePairs) {
if (!pair.collection) continue
await ChatGPTStorage.collection(pair.collection).deleteAll()
}
}
// 备份并清空历史数据
if (fs.existsSync(ChatGPTHistoryStorage.filePath)) {
fs.copyFileSync(
ChatGPTHistoryStorage.filePath,
path.join(backupDir, `history-backup-${timestamp}.json`)
)
// 清空历史数据
for (const collectionName of ChatGPTHistoryStorage.listCollections()) {
await ChatGPTHistoryStorage.collection(collectionName).deleteAll()
}
}
logger.debug(`迁移完成,原数据已备份至 ${backupDir} 目录`)
} catch (error) {
logger.error('数据迁移过程中发生错误:', error)
}
}

View file

@ -0,0 +1,440 @@
import { ChaiteStorage, ProcessorDTO } from 'chaite'
import sqlite3 from 'sqlite3'
import path from 'path'
import fs from 'fs'
import { generateId } from '../../../../utils/common.js'
/**
* @extends {ChaiteStorage<import('chaite').ProcessorDTO>}
*/
export class SQLiteProcessorsStorage extends ChaiteStorage {
getName () {
return 'SQLiteProcessorsStorage'
}
/**
*
* @param {string} dbPath 数据库文件路径
*/
constructor (dbPath) {
super()
this.dbPath = dbPath
this.db = null
this.initialized = false
this.tableName = 'processors'
}
/**
* 初始化数据库连接和表结构
* @returns {Promise<void>}
*/
async initialize () {
if (this.initialized) return
return new Promise((resolve, reject) => {
// 确保<E7A1AE><E4BF9D>录存在
const dir = path.dirname(this.dbPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
this.db = new sqlite3.Database(this.dbPath, async (err) => {
if (err) {
return reject(err)
}
// 创建处理器表,将主要属性分列存储
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
type TEXT NOT NULL,
code TEXT,
cloudId INTEGER,
createdAt TEXT,
updatedAt TEXT,
md5 TEXT,
embedded INTEGER DEFAULT 0,
uploader TEXT,
extraData TEXT
)`, (err) => {
if (err) {
return reject(err)
}
// 创建索引
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_type ON ${this.tableName} (type)`, (err) => {
if (err) {
return reject(err)
}
this.initialized = true
resolve()
})
})
})
})
}
/**
* 确保数据库已初始化
*/
async ensureInitialized () {
if (!this.initialized) {
await this.initialize()
}
}
/**
* ProcessorDTO 对象转换为数据库记录
* @param {import('chaite').ProcessorDTO} processor
* @returns {Object} 数据库记录
*/
_processorToRecord (processor) {
// 提取主要字段
const {
id, name, description, type, code, cloudId,
createdAt, updatedAt, md5, embedded, uploader, ...rest
} = processor
return {
id: id || '',
name: name || '',
description: description || '',
type: type || '', // 'pre' 或 'post'
code: code || '',
cloudId: cloudId || null,
createdAt: createdAt || '',
updatedAt: updatedAt || '',
md5: md5 || '',
embedded: embedded ? 1 : 0,
uploader: uploader ? JSON.stringify(uploader) : null,
extraData: Object.keys(rest).length > 0 ? JSON.stringify(rest) : null
}
}
/**
* 将数据库记录转换为 ProcessorDTO 对象
* @param {Object} record 数据库记录
* @returns {import('chaite').ProcessorDTO} ProcessorDTO 对象
*/
_recordToProcessor (record) {
if (!record) return null
// 解析 JSON 字段
let uploader = null
try {
if (record.uploader) {
uploader = JSON.parse(record.uploader)
}
} catch (e) {
// 解析错误,使用 null
}
let extraData = {}
try {
if (record.extraData) {
extraData = JSON.parse(record.extraData)
}
} catch (e) {
// 解析错误,使用空对象
}
// 构造 ProcessorDTO 对象
const processorData = {
id: record.id,
name: record.name,
description: record.description,
type: record.type, // 'pre' 或 'post'
code: record.code,
cloudId: record.cloudId,
createdAt: record.createdAt,
updatedAt: record.updatedAt,
md5: record.md5,
embedded: Boolean(record.embedded),
uploader,
...extraData
}
return new ProcessorDTO(processorData)
}
/**
* 获取单个处理器
* @param {string} key 处理器ID
* @returns {Promise<import('chaite').ProcessorDTO>}
*/
async getItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
if (err) {
return reject(err)
}
const processor = this._recordToProcessor(row)
resolve(processor)
})
})
}
/**
* 保存处理器
* @param {string} id 处理器ID
* @param {import('chaite').ProcessorDTO} processor 处理器对象
* @returns {Promise<string>}
*/
async setItem (id, processor) {
await this.ensureInitialized()
if (!id) {
id = generateId()
}
// 加上时间戳
if (!processor.createdAt) {
processor.createdAt = new Date().toISOString()
}
processor.updatedAt = new Date().toISOString()
// 转换为数据库记录
const record = this._processorToRecord(processor)
record.id = id // 确保ID是指定的ID
// 构建插入或更新SQL
const fields = Object.keys(record)
const placeholders = fields.map(() => '?').join(', ')
const updates = fields.map(field => `${field} = ?`).join(', ')
const values = fields.map(field => record[field])
const duplicateValues = [...values] // 用于ON CONFLICT时的更新
return new Promise((resolve, reject) => {
this.db.run(
`INSERT INTO ${this.tableName} (${fields.join(', ')})
VALUES (${placeholders})
ON CONFLICT(id) DO UPDATE SET ${updates}`,
[...values, ...duplicateValues],
function (err) {
if (err) {
return reject(err)
}
resolve(id)
}
)
})
}
/**
* 删除处<EFBFBD><EFBFBD><EFBFBD>
* @param {string} key 处理器ID
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 查询所有处理器
* @returns {Promise<import('chaite').ProcessorDTO[]>}
*/
async listItems () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
if (err) {
return reject(err)
}
const processors = rows.map(row => this._recordToProcessor(row)).filter(Boolean)
resolve(processors)
})
})
}
/**
* 根据条件筛选处理器
* @param {Record<string, unknown>} filter 筛选条件
* @returns {Promise<import('chaite').ProcessorDTO[]>}
*/
async listItemsByEqFilter (filter) {
await this.ensureInitialized()
// 如果没有筛选条件,返回所有
if (!filter || Object.keys(filter).length === 0) {
return this.listItems()
}
// 尝试使用SQL字段直接过滤
const directFields = ['id', 'name', 'description', 'type', 'cloudId']
const sqlFilters = []
const sqlParams = []
const extraFilters = {}
let hasExtraFilters = false
// 区分数据库字段和额外字段
for (const key in filter) {
const value = filter[key]
// 如果是直接支持的字段构建SQL条件
if (directFields.includes(key)) {
sqlFilters.push(`${key} = ?`)
sqlParams.push(value)
} else if (key === 'embedded') {
// embedded 字段需要特殊处理为 0/1
sqlFilters.push('embedded = ?')
sqlParams.push(value ? 1 : 0)
} else {
// 其他字段需要在结果中进一步过滤
extraFilters[key] = value
hasExtraFilters = true
}
}
// 构建SQL查询
let sql = `SELECT * FROM ${this.tableName}`
if (sqlFilters.length > 0) {
sql += ` WHERE ${sqlFilters.join(' AND ')}`
}
return new Promise((resolve, reject) => {
this.db.all(sql, sqlParams, (err, rows) => {
if (err) {
return reject(err)
}
let processors = rows.map(row => this._recordToProcessor(row)).filter(Boolean)
// 如果有需要在内存中过滤的额外字段
if (hasExtraFilters) {
processors = processors.filter(processor => {
for (const key in extraFilters) {
if (processor[key] !== extraFilters[key]) {
return false
}
}
return true
})
}
resolve(processors)
})
})
}
/**
* 根据IN条<EFBFBD><EFBFBD>筛选处理器
* @param {Array<{ field: string; values: unknown[]; }>} query
* @returns {Promise<import('chaite').ProcessorDTO[]>}
*/
async listItemsByInQuery (query) {
await this.ensureInitialized()
// 如果没有查询条件,返回所有
if (!query || query.length === 0) {
return this.listItems()
}
// 尝试使用SQL IN子句来优化查询
const directFields = ['id', 'name', 'description', 'type', 'cloudId']
const sqlFilters = []
const sqlParams = []
const extraQueries = []
// 处理每个查询条件
for (const { field, values } of query) {
if (values.length === 0) continue
// 如果是直接支持的字段使用SQL IN子句
if (directFields.includes(field)) {
const placeholders = values.map(() => '?').join(', ')
sqlFilters.push(`${field} IN (${placeholders})`)
sqlParams.push(...values)
} else if (field === 'embedded') {
// embedded 字段需要特殊处理
const boolValues = values.map(v => v ? 1 : 0)
const placeholders = boolValues.map(() => '?').join(', ')
sqlFilters.push(`embedded IN (${placeholders})`)
sqlParams.push(...boolValues)
} else {
// 其他字段在内存中过滤
extraQueries.push({ field, values })
}
}
// 构建SQL查询
let sql = `SELECT * FROM ${this.tableName}`
if (sqlFilters.length > 0) {
sql += ` WHERE ${sqlFilters.join(' AND ')}`
}
return new Promise((resolve, reject) => {
this.db.all(sql, sqlParams, (err, rows) => {
if (err) {
return reject(err)
}
let processors = rows.map(row => this._recordToProcessor(row)).filter(Boolean)
// 如果有需要在内存中过滤的条件
if (extraQueries.length > 0) {
processors = processors.filter(processor => {
for (const { field, values } of extraQueries) {
if (!values.includes(processor[field])) {
return false
}
}
return true
})
}
resolve(processors)
})
})
}
/**
* 清空表中所有数据
* @returns {Promise<void>}
*/
async clear () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 关闭数据库连接
* @returns {Promise<void>}
*/
async close () {
if (!this.db) return Promise.resolve()
return new Promise((resolve, reject) => {
this.db.close(err => {
if (err) {
reject(err)
} else {
this.initialized = false
this.db = null
resolve()
}
})
})
}
}

View file

@ -0,0 +1,569 @@
import { ChaiteStorage } from 'chaite'
import sqlite3 from 'sqlite3'
import path from 'path'
import fs from 'fs'
import { generateId } from '../../../../utils/common.js'
/**
* @extends {ChaiteStorage<import('chaite').ToolsGroupDTO>}
*/
export class SQLiteToolsGroupStorage extends ChaiteStorage {
getName () {
return 'SQLiteToolsGroupStorage'
}
/**
* @param {string} dbPath 数据库文件路径
*/
constructor (dbPath) {
super()
this.dbPath = dbPath
this.db = null
this.initialized = false
this.tableName = 'tools_groups'
}
/**
* 初始化数据库连接和表结构
*/
async initialize () {
if (this.initialized) return
return new Promise((resolve, reject) => {
const dir = path.dirname(this.dbPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
this.db = new sqlite3.Database(this.dbPath, async (err) => {
if (err) return reject(err)
try {
// 首先检查表是否存在
const tableExists = await this.checkTableExists()
if (tableExists) {
// 如果表存在,检查并迁移旧结构
await this.migrateTableIfNeeded()
} else {
// 如果表不存在,创建新表
await this.createTable()
}
// 确保索引存在
await this.ensureIndex()
this.initialized = true
resolve()
} catch (error) {
reject(error)
}
})
})
}
/**
* 检查表是否存在
*/
async checkTableExists () {
return new Promise((resolve, reject) => {
this.db.get(
'SELECT name FROM sqlite_master WHERE type=\'table\' AND name=?',
[this.tableName],
(err, row) => {
if (err) return reject(err)
resolve(!!row)
}
)
})
}
/**
* 创建新表
*/
async createTable () {
return new Promise((resolve, reject) => {
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
toolIds TEXT NOT NULL,
isDefault INTEGER DEFAULT 0,
createdAt TEXT,
updatedAt TEXT
)`, (err) => {
if (err) return reject(err)
resolve()
})
})
}
/**
* 确保索引存在
*/
async ensureIndex () {
return new Promise((resolve, reject) => {
this.db.run(`CREATE INDEX IF NOT EXISTS idx_tools_groups_name ON ${this.tableName} (name)`, (err) => {
if (err) return reject(err)
resolve()
})
})
}
/**
* 检查并迁移表结构
*/
async migrateTableIfNeeded () {
// 检查表结构
const columns = await this.getTableColumns()
// 检查是否有旧版本的结构有tools字段而不是toolIds
const hasOldStructure = columns.includes('tools') && !columns.includes('toolIds')
const needsDefaultColumn = !columns.includes('isDefault')
if (hasOldStructure || needsDefaultColumn) {
console.log(`检测到旧表结构,开始迁移 ${this.tableName} 表...`)
// 备份所有数据
const allData = await this.backupData()
// 重命名旧表
await this.renameTable(`${this.tableName}_old`)
// 创建新表
await this.createTable()
await this.ensureIndex()
// 恢复数据到新表
if (allData.length > 0) {
await this.restoreData(allData, hasOldStructure)
}
// 删除旧表
await this.dropTable(`${this.tableName}_old`)
console.log(`${this.tableName} 迁移完成,共迁移 ${allData.length} 条数据`)
}
}
/**
* 获取表的所有列名
*/
async getTableColumns () {
return new Promise((resolve, reject) => {
this.db.all(`PRAGMA table_info(${this.tableName})`, (err, rows) => {
if (err) return reject(err)
const columns = rows.map(row => row.name)
resolve(columns)
})
})
}
/**
* 备份表数据
*/
async backupData () {
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
if (err) return reject(err)
resolve(rows)
})
})
}
/**
* 重命名表
*/
async renameTable (newName) {
return new Promise((resolve, reject) => {
this.db.run(`ALTER TABLE ${this.tableName} RENAME TO ${newName}`, (err) => {
if (err) return reject(err)
resolve()
})
})
}
/**
* 删除表
*/
async dropTable (tableName) {
return new Promise((resolve, reject) => {
this.db.run(`DROP TABLE IF EXISTS ${tableName}`, (err) => {
if (err) return reject(err)
resolve()
})
})
}
/**
* 恢复数据到新表
*/
async restoreData (data, hasOldStructure) {
const promises = data.map(row => {
return new Promise((resolve, reject) => {
// 处理数据转换
const newRow = { ...row }
if (hasOldStructure && row.tools) {
try {
// 从旧的tools结构提取toolIds
const tools = JSON.parse(row.tools)
newRow.toolIds = JSON.stringify(tools.map(t => t.id || t))
delete newRow.tools
} catch (e) {
console.error(`解析工具组数据错误: ${row.id}`, e)
newRow.toolIds = JSON.stringify([])
delete newRow.tools
}
}
// 添加isDefault字段
if (newRow.isDefault === undefined) {
newRow.isDefault = 0
}
// 添加时间戳
if (!newRow.createdAt) {
newRow.createdAt = new Date().toISOString()
}
if (!newRow.updatedAt) {
newRow.updatedAt = new Date().toISOString()
}
const fields = Object.keys(newRow)
const placeholders = fields.map(() => '?').join(',')
const values = fields.map(field => newRow[field])
this.db.run(
`INSERT INTO ${this.tableName} (${fields.join(',')}) VALUES (${placeholders})`,
values,
(err) => {
if (err) return reject(err)
resolve()
}
)
})
})
return Promise.all(promises)
}
async ensureInitialized () {
if (!this.initialized) {
await this.initialize()
}
}
/**
* 获取工具组
* @param {string} key 工具组ID
*/
async getItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
if (err) return reject(err)
if (!row) return resolve(null)
try {
const toolsGroup = {
...row,
toolIds: JSON.parse(row.toolIds),
isDefault: Boolean(row.isDefault)
}
resolve(toolsGroup)
} catch (e) {
console.error(`解析工具组数据错误: ${key}`, e)
resolve({
...row,
toolIds: [],
isDefault: Boolean(row.isDefault)
})
}
})
})
}
/**
* 保存工具组
* @param {string} id 工具组ID
* @param {Object} data 工具组数据
*/
async setItem (id, data) {
await this.ensureInitialized()
if (!id) {
id = generateId()
}
// 加上时间戳
if (!data.createdAt) {
data.createdAt = new Date().toISOString()
}
data.updatedAt = new Date().toISOString()
// 提取工具组数据
const { name, description, toolIds, isDefault } = data
const updatedAt = new Date().toISOString()
// 将工具ID列表序列化为JSON字符串
const toolIdsJson = JSON.stringify(toolIds || [])
const isDefaultValue = isDefault ? 1 : 0
return new Promise((resolve, reject) => {
// 检查工具组是否已存在
this.db.get(`SELECT id FROM ${this.tableName} WHERE id = ?`, [id], (err, row) => {
if (err) {
return reject(err)
}
if (row) {
// 更新现有工具组
this.db.run(
`UPDATE ${this.tableName} SET name = ?, description = ?, toolIds = ?, isDefault = ?, updatedAt = ? WHERE id = ?`,
[name, description, toolIdsJson, isDefaultValue, updatedAt, id],
(err) => {
if (err) {
return reject(err)
}
resolve(id)
}
)
} else {
// 插入新工具组
this.db.run(
`INSERT INTO ${this.tableName} (id, name, description, toolIds, isDefault, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?)`,
[id, name, description, toolIdsJson, isDefaultValue, data.createdAt, updatedAt],
(err) => {
if (err) {
return reject(err)
}
resolve(id)
}
)
}
})
})
}
/**
* 删除工具组
* @param {string} key 工具组ID
*/
async removeItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], function (err) {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 获取所有工具组
*/
async listItems () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
if (err) {
return reject(err)
}
const toolsGroups = rows.map(row => {
try {
return {
...row,
toolIds: JSON.parse(row.toolIds),
isDefault: Boolean(row.isDefault)
}
} catch (e) {
console.error(`解析工具组数据错误: ${row.id}`, e)
return {
...row,
toolIds: [],
isDefault: Boolean(row.isDefault)
}
}
})
resolve(toolsGroups)
})
})
}
/**
* 根据条件筛选工具组
* @param {Record<string, unknown>} filter 筛选条件
*/
async listItemsByEqFilter (filter) {
await this.ensureInitialized()
if (!filter || Object.keys(filter).length === 0) {
return this.listItems()
}
const directFields = ['id', 'name', 'description']
const conditions = []
const params = []
for (const key in filter) {
if (directFields.includes(key)) {
conditions.push(`${key} = ?`)
params.push(filter[key])
} else if (key === 'isDefault') {
conditions.push('isDefault = ?')
params.push(filter[key] ? 1 : 0)
}
}
const sql = conditions.length > 0
? `SELECT * FROM ${this.tableName} WHERE ${conditions.join(' AND ')}`
: `SELECT * FROM ${this.tableName}`
return new Promise((resolve, reject) => {
this.db.all(sql, params, (err, rows) => {
if (err) return reject(err)
const toolsGroups = rows.map(row => {
try {
const group = {
...row,
toolIds: JSON.parse(row.toolIds || '[]'),
isDefault: Boolean(row.isDefault)
}
// 过滤其他字段
for (const key in filter) {
if (!directFields.includes(key) &&
key !== 'isDefault' &&
JSON.stringify(group[key]) !== JSON.stringify(filter[key])) {
return null
}
}
return group
} catch (e) {
console.error(`解析工具组数据错误: ${row.id}`, e)
return null
}
}).filter(Boolean)
resolve(toolsGroups)
})
})
}
/**
* 根据IN条件筛选工具组
* @param {Array<{field: string, values: unknown[]}>} query IN查询条件
*/
async listItemsByInQuery (query) {
await this.ensureInitialized()
if (!query || query.length === 0) {
return this.listItems()
}
const directFields = ['id', 'name', 'description']
const conditions = []
const params = []
const memoryQueries = []
for (const item of query) {
if (directFields.includes(item.field) && Array.isArray(item.values) && item.values.length > 0) {
const placeholders = item.values.map(() => '?').join(',')
conditions.push(`${item.field} IN (${placeholders})`)
params.push(...item.values)
} else if (item.field === 'isDefault' && Array.isArray(item.values) && item.values.length > 0) {
const boolValues = item.values.map(v => v ? 1 : 0)
const placeholders = boolValues.map(() => '?').join(',')
conditions.push(`isDefault IN (${placeholders})`)
params.push(...boolValues)
} else if (item.values.length > 0) {
memoryQueries.push(item)
}
}
const sql = conditions.length > 0
? `SELECT * FROM ${this.tableName} WHERE ${conditions.join(' AND ')}`
: `SELECT * FROM ${this.tableName}`
return new Promise((resolve, reject) => {
this.db.all(sql, params, (err, rows) => {
if (err) return reject(err)
let toolsGroups = rows.map(row => {
try {
return {
...row,
toolIds: JSON.parse(row.toolIds || '[]'),
isDefault: Boolean(row.isDefault)
}
} catch (e) {
console.error(`解析工具组数据错误: ${row.id}`, e)
return null
}
}).filter(Boolean)
// 内存中过滤其它字段
if (memoryQueries.length > 0) {
toolsGroups = toolsGroups.filter(group => {
for (const { field, values } of memoryQueries) {
// 对于toolIds字段做特殊处理
if (field === 'toolIds') {
const hasMatch = values.some(toolId => group.toolIds.includes(toolId))
if (!hasMatch) return false
} else if (!values.includes(group[field])) {
return false
}
}
return true
})
}
resolve(toolsGroups)
})
})
}
/**
* 清空所有工具组
*/
async clear () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
if (err) return reject(err)
resolve()
})
})
}
/**
* 关闭数据库连接
*/
async close () {
if (!this.db) return Promise.resolve()
return new Promise((resolve, reject) => {
this.db.close(err => {
if (err) {
reject(err)
} else {
this.initialized = false
this.db = null
resolve()
}
})
})
}
}

View file

@ -0,0 +1,467 @@
import { ChaiteStorage, ToolDTO } from 'chaite'
import sqlite3 from 'sqlite3'
import path from 'path'
import fs from 'fs'
import { generateId } from '../../../../utils/common.js'
/**
* @extends {ChaiteStorage<import('chaite').ToolDTO>}
*/
export class SQLiteToolsStorage extends ChaiteStorage {
getName () {
return 'SQLiteToolsStorage'
}
/**
*
* @param {string} dbPath 数据库文件路径
*/
constructor (dbPath) {
super()
this.dbPath = dbPath
this.db = null
this.initialized = false
this.tableName = 'tools'
}
/**
* 初始化数据库连接和表结构
* @returns {Promise<void>}
*/
async initialize () {
if (this.initialized) return
return new Promise((resolve, reject) => {
// 确保目录存在
const dir = path.dirname(this.dbPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
this.db = new sqlite3.Database(this.dbPath, async (err) => {
if (err) {
return reject(err)
}
// 创建工具表,将主要属性分列存储
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
modelType TEXT,
code TEXT,
cloudId INTEGER,
embedded INTEGER,
uploader TEXT,
createdAt TEXT,
updatedAt TEXT,
md5 TEXT,
status TEXT,
permission TEXT,
extraData TEXT -- 存储其他额外数据的JSON
)`, (err) => {
if (err) {
reject(err)
} else {
// 创建索引以提高查询性能
this.db.run(`CREATE INDEX IF NOT EXISTS idx_tools_name ON ${this.tableName} (name)`, (err) => {
if (err) {
reject(err)
} else {
this.db.run(`CREATE INDEX IF NOT EXISTS idx_tools_status ON ${this.tableName} (status)`, (err) => {
if (err) {
reject(err)
} else {
this.db.run(`CREATE INDEX IF NOT EXISTS idx_tools_permission ON ${this.tableName} (permission)`, (err) => {
if (err) {
reject(err)
} else {
this.initialized = true
resolve()
}
})
}
})
}
})
}
})
})
})
}
/**
* 确保数据库已初始化
*/
async ensureInitialized () {
if (!this.initialized) {
await this.initialize()
}
}
/**
* ToolDTO 对象转换为数据库记录
* @param {import('chaite').ToolDTO} tool
* @returns {Object} 数据库记录
*/
_toolToRecord (tool) {
// 提取主要字段剩余的放入extraData
const {
id, name, description, modelType, code, cloudId,
embedded, uploader, createdAt, updatedAt, md5,
status, permission, ...rest
} = tool
// 序列化上传者对象
const uploaderStr = uploader ? JSON.stringify(uploader) : null
return {
id: id || '',
name: name || '',
description: description || '',
modelType: modelType || '',
code: code || null,
cloudId: cloudId || null,
embedded: embedded ? 1 : 0,
uploader: uploaderStr,
createdAt: createdAt || '',
updatedAt: updatedAt || '',
md5: md5 || '',
status: status || 'enabled',
permission: permission || 'public',
extraData: Object.keys(rest).length > 0 ? JSON.stringify(rest) : null
}
}
/**
* 将数据库记录转换为 ToolDTO 对象
* @param {Object} record 数据库记录
* @returns {import('chaite').ToolDTO} ToolDTO对象
*/
_recordToTool (record) {
// 若记录不存在则返回null
if (!record) return null
// 解析上传者
let uploader = null
try {
if (record.uploader) {
uploader = JSON.parse(record.uploader)
}
} catch (e) {
// 解析错误使用null
}
// 解析额外数据
let extraData = {}
try {
if (record.extraData) {
extraData = JSON.parse(record.extraData)
}
} catch (e) {
// 解析错误,使用空对象
}
// 构造基本对象
const toolData = {
id: record.id,
name: record.name,
description: record.description,
modelType: record.modelType,
code: record.code,
cloudId: record.cloudId,
embedded: Boolean(record.embedded),
uploader,
createdAt: record.createdAt,
updatedAt: record.updatedAt,
md5: record.md5,
status: record.status,
permission: record.permission,
...extraData
}
return new ToolDTO(toolData)
}
/**
* 获取单个工具
* @param {string} key 工具ID
* @returns {Promise<import('chaite').ToolDTO>}
*/
async getItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
if (err) {
return reject(err)
}
const tool = this._recordToTool(row)
resolve(tool)
})
})
}
/**
* 保存工具
* @param {string} id 工具ID
* @param {import('chaite').ToolDTO} tool 工具对象
* @returns {Promise<string>}
*/
async setItem (id, tool) {
await this.ensureInitialized()
if (!id) {
id = generateId()
}
// 加上时间戳
if (!tool.createdAt) {
tool.createdAt = new Date().toISOString()
}
tool.updatedAt = new Date().toISOString()
// 转换为数据库记录
const record = this._toolToRecord(tool)
record.id = id // 确保ID是指定的ID
// 构建插入或更新SQL
const fields = Object.keys(record)
const placeholders = fields.map(() => '?').join(', ')
const updates = fields.map(field => `${field} = ?`).join(', ')
const values = fields.map(field => record[field])
const duplicateValues = [...values] // 用于ON CONFLICT时的更新
return new Promise((resolve, reject) => {
this.db.run(
`INSERT INTO ${this.tableName} (${fields.join(', ')})
VALUES (${placeholders})
ON CONFLICT(id) DO UPDATE SET ${updates}`,
[...values, ...duplicateValues],
function (err) {
if (err) {
return reject(err)
}
resolve(id)
}
)
})
}
/**
* 删除工具
* @param {string} key 工具ID
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 查询所有工具
* @returns {Promise<import('chaite').ToolDTO[]>}
*/
async listItems () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
if (err) {
return reject(err)
}
const tools = rows.map(row => this._recordToTool(row)).filter(Boolean)
resolve(tools)
})
})
}
/**
* 根据条件筛选工具直接使用SQL查询避免全表扫描
* @param {Record<string, unknown>} filter 筛选条件
* @returns {Promise<import('chaite').ToolDTO[]>}
*/
async listItemsByEqFilter (filter) {
await this.ensureInitialized()
// 如果没有筛选条件,返回所有
if (!filter || Object.keys(filter).length === 0) {
return this.listItems()
}
// 尝试使用SQL字段直接过滤
const directFields = ['id', 'name', 'description', 'modelType', 'cloudId', 'status', 'permission']
const sqlFilters = []
const sqlParams = []
const extraFilters = {}
let hasExtraFilters = false
// 区分数据库字段和额外字段
for (const key in filter) {
const value = filter[key]
// 如果是直接支持的字段构建SQL条件
if (directFields.includes(key)) {
sqlFilters.push(`${key} = ?`)
sqlParams.push(value)
} else if (key === 'embedded') {
// embedded 字段需要特殊处理为 0/1
sqlFilters.push('embedded = ?')
sqlParams.push(value ? 1 : 0)
} else {
// 其他字段需要在结果中进一步过滤
extraFilters[key] = value
hasExtraFilters = true
}
}
// 构建SQL查询
let sql = `SELECT * FROM ${this.tableName}`
if (sqlFilters.length > 0) {
sql += ` WHERE ${sqlFilters.join(' AND ')}`
}
return new Promise((resolve, reject) => {
this.db.all(sql, sqlParams, (err, rows) => {
if (err) {
return reject(err)
}
let tools = rows.map(row => this._recordToTool(row)).filter(Boolean)
// 如果有需要在内存中过滤的额外字段
if (hasExtraFilters) {
tools = tools.filter(tool => {
for (const key in extraFilters) {
if (tool[key] !== extraFilters[key]) {
return false
}
}
return true
})
}
resolve(tools)
})
})
}
/**
* 根据IN条件筛选工具
* @param {Array<{ field: string; values: unknown[]; }>} query
* @returns {Promise<import('chaite').ToolDTO[]>}
*/
async listItemsByInQuery (query) {
await this.ensureInitialized()
// 如果没有查询条件,返回所有
if (!query || query.length === 0) {
return this.listItems()
}
// 尝试使用SQL IN子句来优化查询
const directFields = ['id', 'name', 'description', 'modelType', 'cloudId', 'status', 'permission']
const sqlFilters = []
const sqlParams = []
const extraQueries = []
// 处理每个查询条件
for (const { field, values } of query) {
if (values.length === 0) continue
// 如果是直接支持的字段使用SQL IN子句
if (directFields.includes(field)) {
const placeholders = values.map(() => '?').join(', ')
sqlFilters.push(`${field} IN (${placeholders})`)
sqlParams.push(...values)
// embedded 字段需要特殊处理
} else if (field === 'embedded') {
const boolValues = values.map(v => v ? 1 : 0)
const placeholders = boolValues.map(() => '?').join(', ')
sqlFilters.push(`embedded IN (${placeholders})`)
sqlParams.push(...boolValues)
} else {
// 其他字段在内存中过滤
extraQueries.push({ field, values })
}
}
// 构建SQL查询
let sql = `SELECT * FROM ${this.tableName}`
if (sqlFilters.length > 0) {
sql += ` WHERE ${sqlFilters.join(' AND ')}`
}
return new Promise((resolve, reject) => {
this.db.all(sql, sqlParams, (err, rows) => {
if (err) {
return reject(err)
}
let tools = rows.map(row => this._recordToTool(row)).filter(Boolean)
// 如果有需要在内存中过滤的条件
if (extraQueries.length > 0) {
tools = tools.filter(tool => {
for (const { field, values } of extraQueries) {
if (!values.includes(tool[field])) {
return false
}
}
return true
})
}
resolve(tools)
})
})
}
/**
* 清空表中所有数据
* @returns {Promise<void>}
*/
async clear () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 关闭数据库连接
* @returns {Promise<void>}
*/
async close () {
if (!this.db) return Promise.resolve()
return new Promise((resolve, reject) => {
this.db.close(err => {
if (err) {
reject(err)
} else {
this.initialized = false
this.db = null
resolve()
}
})
})
}
}

View file

@ -0,0 +1,474 @@
import { ChaiteStorage, TriggerDTO } from 'chaite'
import sqlite3 from 'sqlite3'
import path from 'path'
import fs from 'fs'
import { generateId } from '../../../../utils/common.js'
/**
* @extends {ChaiteStorage<import('chaite').TriggerDTO>}
*/
export class SQLiteTriggerStorage extends ChaiteStorage {
getName () {
return 'SQLiteTriggerStorage'
}
/**
*
* @param {string} dbPath 数据库文件路径
*/
constructor (dbPath) {
super()
this.dbPath = dbPath
this.db = null
this.initialized = false
this.tableName = 'triggers'
}
/**
* 初始化数据库连接和表结构
* @returns {Promise<void>}
*/
async initialize () {
if (this.initialized) return
return new Promise((resolve, reject) => {
// 确保目录存在
const dir = path.dirname(this.dbPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
this.db = new sqlite3.Database(this.dbPath, async (err) => {
if (err) {
return reject(err)
}
// 创建触发器表,将主要属性分列存储
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
modelType TEXT,
code TEXT,
cloudId INTEGER,
embedded INTEGER,
uploader TEXT,
createdAt TEXT,
updatedAt TEXT,
md5 TEXT,
status TEXT,
permission TEXT,
isOneTime INTEGER,
extraData TEXT -- 存储其他额外数据的JSON
)`, (err) => {
if (err) {
reject(err)
} else {
// 创建索引以提高查询性能
this.db.run(`CREATE INDEX IF NOT EXISTS idx_triggers_name ON ${this.tableName} (name)`, (err) => {
if (err) {
reject(err)
} else {
this.db.run(`CREATE INDEX IF NOT EXISTS idx_triggers_status ON ${this.tableName} (status)`, (err) => {
if (err) {
reject(err)
} else {
this.initialized = true
resolve()
}
})
}
})
}
})
})
})
}
/**
* 确保数据库已初始化
*/
async ensureInitialized () {
if (!this.initialized) {
await this.initialize()
}
}
/**
* TriggerDTO 对象转换为数据库记录
* @param {import('chaite').TriggerDTO} trigger
* @returns {Object} 数据库记录
*/
_triggerToRecord (trigger) {
// 提取主要字段剩余的放入extraData
const {
id, name, description, modelType, code, cloudId,
embedded, uploader, createdAt, updatedAt, md5,
status, permission, isOneTime, ...rest
} = trigger
// 序列化上传者对象
const uploaderStr = uploader ? JSON.stringify(uploader) : null
return {
id: id || '',
name: name || '',
description: description || '',
modelType: modelType || 'executable',
code: code || null,
cloudId: cloudId || null,
embedded: embedded ? 1 : 0,
uploader: uploaderStr,
createdAt: createdAt || '',
updatedAt: updatedAt || '',
md5: md5 || '',
status: status || 'enabled',
permission: permission || 'public',
isOneTime: isOneTime ? 1 : 0,
extraData: Object.keys(rest).length > 0 ? JSON.stringify(rest) : null
}
}
/**
* 将数据库记录转换为 TriggerDTO 对象
* @param {Object} record 数据库记录
* @returns {import('chaite').TriggerDTO} TriggerDTO对象
*/
_recordToTrigger (record) {
// 若记录不存在则返回null
if (!record) return null
// 解析上传者
let uploader = null
try {
if (record.uploader) {
uploader = JSON.parse(record.uploader)
}
} catch (e) {
// 解析错误使用null
}
// 解析额外数据
let extraData = {}
try {
if (record.extraData) {
extraData = JSON.parse(record.extraData)
}
} catch (e) {
// 解析错误,使用空对象
}
// 构造基本对象
const triggerData = {
id: record.id,
name: record.name,
description: record.description,
modelType: record.modelType,
code: record.code,
cloudId: record.cloudId,
embedded: Boolean(record.embedded),
uploader,
createdAt: record.createdAt,
updatedAt: record.updatedAt,
md5: record.md5,
status: record.status,
permission: record.permission,
isOneTime: Boolean(record.isOneTime),
...extraData
}
return new TriggerDTO(triggerData)
}
/**
* 获取单个触发器
* @param {string} key 触发器ID
* @returns {Promise<import('chaite').TriggerDTO>}
*/
async getItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
if (err) {
return reject(err)
}
const trigger = this._recordToTrigger(row)
resolve(trigger)
})
})
}
/**
* 保存触发器
* @param {string} id 触发器ID
* @param {import('chaite').TriggerDTO} trigger 触发器对象
* @returns {Promise<string>}
*/
async setItem (id, trigger) {
await this.ensureInitialized()
if (!id) {
id = generateId()
}
// 加上时间戳
if (!trigger.createdAt) {
trigger.createdAt = new Date().toISOString()
}
trigger.updatedAt = new Date().toISOString()
// 转换为数据库记录
const record = this._triggerToRecord(trigger)
record.id = id // 确保ID是指定的ID
// 构建插入或更新SQL
const fields = Object.keys(record)
const placeholders = fields.map(() => '?').join(', ')
const updates = fields.map(field => `${field} = ?`).join(', ')
const values = fields.map(field => record[field])
const duplicateValues = [...values] // 用于ON CONFLICT时的更新
return new Promise((resolve, reject) => {
this.db.run(
`INSERT INTO ${this.tableName} (${fields.join(', ')})
VALUES (${placeholders})
ON CONFLICT(id) DO UPDATE SET ${updates}`,
[...values, ...duplicateValues],
function (err) {
if (err) {
return reject(err)
}
resolve(id)
}
)
})
}
/**
* 删除触发器
* @param {string} key 触发器ID
* @returns {Promise<void>}
*/
async removeItem (key) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 查询所有触发器
* @returns {Promise<import('chaite').TriggerDTO[]>}
*/
async listItems () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
if (err) {
return reject(err)
}
const triggers = rows.map(row => this._recordToTrigger(row)).filter(Boolean)
resolve(triggers)
})
})
}
/**
* 根据条件筛选触发器
* @param {Record<string, unknown>} filter 筛选条件
* @returns {Promise<import('chaite').TriggerDTO[]>}
*/
async listItemsByEqFilter (filter) {
await this.ensureInitialized()
// 如果没有筛选条件,返回所有
if (!filter || Object.keys(filter).length === 0) {
return this.listItems()
}
// 尝试使用SQL字段直接过滤
const directFields = ['id', 'name', 'description', 'modelType', 'cloudId', 'status', 'permission']
const sqlFilters = []
const sqlParams = []
const extraFilters = {}
let hasExtraFilters = false
// 区分数据库字段和额外字段
for (const key in filter) {
const value = filter[key]
// 如果是直接支持的字段构建SQL条件
if (directFields.includes(key)) {
sqlFilters.push(`${key} = ?`)
sqlParams.push(value)
} else if (key === 'embedded') {
// embedded 字段需要特殊处理为 0/1
sqlFilters.push('embedded = ?')
sqlParams.push(value ? 1 : 0)
} else if (key === 'isOneTime') {
// isOneTime 字段需要特殊处理为 0/1
sqlFilters.push('isOneTime = ?')
sqlParams.push(value ? 1 : 0)
} else {
// 其他字段需要在结果中进一步过滤
extraFilters[key] = value
hasExtraFilters = true
}
}
// 构建SQL查询
let sql = `SELECT * FROM ${this.tableName}`
if (sqlFilters.length > 0) {
sql += ` WHERE ${sqlFilters.join(' AND ')}`
}
return new Promise((resolve, reject) => {
this.db.all(sql, sqlParams, (err, rows) => {
if (err) {
return reject(err)
}
let triggers = rows.map(row => this._recordToTrigger(row)).filter(Boolean)
// 如果有需要在内存中过滤的额外字段
if (hasExtraFilters) {
triggers = triggers.filter(trigger => {
for (const key in extraFilters) {
if (trigger[key] !== extraFilters[key]) {
return false
}
}
return true
})
}
resolve(triggers)
})
})
}
/**
* 根据IN条件筛选触发器
* @param {Array<{ field: string; values: unknown[]; }>} query
* @returns {Promise<import('chaite').TriggerDTO[]>}
*/
async listItemsByInQuery (query) {
await this.ensureInitialized()
// 如果没有查询条<E8AFA2><E69DA1><EFBFBD>返回所有
if (!query || query.length === 0) {
return this.listItems()
}
// 尝试使用SQL IN子句来优化查询
const directFields = ['id', 'name', 'description', 'modelType', 'cloudId', 'status', 'permission']
const sqlFilters = []
const sqlParams = []
const extraQueries = []
// 处理每个查询条件
for (const { field, values } of query) {
if (values.length === 0) continue
// 如果是直接支持的字段使用SQL IN子句
if (directFields.includes(field)) {
const placeholders = values.map(() => '?').join(', ')
sqlFilters.push(`${field} IN (${placeholders})`)
sqlParams.push(...values)
} else if (field === 'embedded') {
const boolValues = values.map(v => v ? 1 : 0)
const placeholders = boolValues.map(() => '?').join(', ')
sqlFilters.push(`embedded IN (${placeholders})`)
sqlParams.push(...boolValues)
} else if (field === 'isOneTime') {
const boolValues = values.map(v => v ? 1 : 0)
const placeholders = boolValues.map(() => '?').join(', ')
sqlFilters.push(`isOneTime IN (${placeholders})`)
sqlParams.push(...boolValues)
} else {
// 其他字段在内存中过滤
extraQueries.push({ field, values })
}
}
// 构建SQL查询
let sql = `SELECT * FROM ${this.tableName}`
if (sqlFilters.length > 0) {
sql += ` WHERE ${sqlFilters.join(' AND ')}`
}
return new Promise((resolve, reject) => {
this.db.all(sql, sqlParams, (err, rows) => {
if (err) {
return reject(err)
}
let triggers = rows.map(row => this._recordToTrigger(row)).filter(Boolean)
// 如果有需要在内存中过滤的条件
if (extraQueries.length > 0) {
triggers = triggers.filter(trigger => {
for (const { field, values } of extraQueries) {
if (!values.includes(trigger[field])) {
return false
}
}
return true
})
}
resolve(triggers)
})
})
}
/**
* 清空表中所有数据
* @returns {Promise<void>}
*/
async clear () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 关闭数据库连接
* @returns {Promise<void>}
*/
async close () {
if (!this.db) return Promise.resolve()
return new Promise((resolve, reject) => {
this.db.close(err => {
if (err) {
reject(err)
} else {
this.initialized = false
this.db = null
resolve()
}
})
})
}
}
export default SQLiteTriggerStorage

View file

@ -0,0 +1,388 @@
import { ChaiteStorage } from 'chaite'
import sqlite3 from 'sqlite3'
import path from 'path'
import fs from 'fs'
import crypto from 'node:crypto'
/**
* 基于SQLite的用户状态存储实现
* @extends {ChaiteStorage<import('chaite').UserState>}
*/
export class SQLiteUserStateStorage extends ChaiteStorage {
/**
* 构造函数
* @param {string} dbPath 数据库文件路径
*/
constructor (dbPath) {
super()
this.dbPath = dbPath
this.db = null
this.initialized = false
this.tableName = 'user_states'
}
/**
* 初始化数据库<EFBFBD><EFBFBD>接和表结构
* @returns {Promise<void>}
*/
async initialize () {
if (this.initialized) return
return new Promise((resolve, reject) => {
// 确保目录存在
const dir = path.dirname(this.dbPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
this.db = new sqlite3.Database(this.dbPath, async (err) => {
if (err) {
return reject(err)
}
// 创建用户状态表
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
id TEXT PRIMARY KEY,
userId TEXT NOT NULL,
nickname TEXT,
card TEXT,
conversations TEXT NOT NULL,
settings TEXT NOT NULL,
current TEXT NOT NULL,
updatedAt INTEGER
)`, (err) => {
if (err) {
return reject(err)
}
// 创建索引以加快查询
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_userId ON ${this.tableName} (userId)`, (err) => {
if (err) {
return reject(err)
}
this.initialized = true
resolve()
})
})
})
})
}
/**
* 确保数据库已初始化
*/
async ensureInitialized () {
if (!this.initialized) {
await this.initialize()
}
}
/**
* 获取用户状态
* @param {string} userId 用户ID
* @returns {Promise<import('chaite').UserState|null>}
*/
async getItem (userId) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.get(`SELECT * FROM ${this.tableName} WHERE userId = ?`, [userId], (err, row) => {
if (err) {
return reject(err)
}
if (!row) {
return resolve(null)
}
try {
const userState = {
userId: row.userId,
nickname: row.nickname,
card: row.card,
conversations: JSON.parse(row.conversations),
settings: JSON.parse(row.settings),
current: JSON.parse(row.current)
}
resolve(userState)
} catch (e) {
console.error(`解析用户状态数据错误: ${userId}`, e)
resolve(null)
}
})
})
}
/**
* 保存用户状态
* @param {string} userId 用户ID
* @param {import('chaite').UserState} userState 用户状态数据
* @returns {Promise<string>} 返回用户ID
*/
async setItem (userId, userState) {
await this.ensureInitialized()
// 提取用户状态数据
const { nickname, card, conversations, settings, current } = userState
const updatedAt = Date.now()
// 序列化数据
const conversationsJson = JSON.stringify(conversations || [])
const settingsJson = JSON.stringify(settings || {})
const currentJson = JSON.stringify(current || {})
return new Promise((resolve, reject) => {
// 检查用户状态是否已存在
this.db.get(`SELECT userId FROM ${this.tableName} WHERE userId = ?`, [userId], (err, row) => {
if (err) {
return reject(err)
}
if (row) {
// 更新现有用户状态
this.db.run(
`UPDATE ${this.tableName} SET
nickname = ?,
card = ?,
conversations = ?,
settings = ?,
current = ?,
updatedAt = ?
WHERE userId = ?`,
[nickname, card, conversationsJson, settingsJson, currentJson, updatedAt, userId],
(err) => {
if (err) {
return reject(err)
}
resolve(userId)
}
)
} else {
// 插入新用户状态
this.db.run(
`INSERT INTO ${this.tableName}
(id, userId, nickname, card, conversations, settings, current, updatedAt)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
[crypto.randomUUID(), userId, nickname, card, conversationsJson, settingsJson, currentJson, updatedAt],
(err) => {
if (err) {
return reject(err)
}
resolve(userId)
}
)
}
})
})
}
/**
* 删除用户状态
* @param {string} userId 用户ID
* @returns {Promise<void>}
*/
async removeItem (userId) {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName} WHERE userId = ?`, [userId], (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 获取所有用户状态
* @returns {Promise<import('chaite').UserState[]>}
*/
async listItems () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
if (err) {
return reject(err)
}
const userStates = rows.map(row => {
try {
return {
userId: row.userId,
nickname: row.nickname,
card: row.card,
conversations: JSON.parse(row.conversations),
settings: JSON.parse(row.settings),
current: JSON.parse(row.current)
}
} catch (e) {
console.error(`解析用户状态数据错误: ${row.userId}`, e)
return null
}
}).filter(Boolean)
resolve(userStates)
})
})
}
/**
* 根据过滤条件查询用户状态
* @param {Record<string, unknown>} filter 过滤条件
* @returns {Promise<import('chaite').UserState[]>}
*/
async listItemsByEqFilter (filter) {
await this.ensureInitialized()
// 只支持userId、nickname、card的过滤
const supportedFilters = ['userId', 'nickname', 'card']
const conditions = []
const params = []
for (const key of supportedFilters) {
if (filter[key] !== undefined) {
conditions.push(`${key} = ?`)
params.push(filter[key])
}
}
if (conditions.length === 0) {
return this.listItems()
}
const whereClause = conditions.join(' AND ')
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM ${this.tableName} WHERE ${whereClause}`, params, (err, rows) => {
if (err) {
return reject(err)
}
const userStates = rows.map(row => {
try {
return {
userId: row.userId,
nickname: row.nickname,
card: row.card,
conversations: JSON.parse(row.conversations),
settings: JSON.parse(row.settings),
current: JSON.parse(row.current)
}
} catch (e) {
console.error(`解析用户状态数据错误: ${row.userId}`, e)
return null
}
}).filter(Boolean)
resolve(userStates)
})
})
}
/**
* 根据IN查询条件查询用户状<EFBFBD><EFBFBD>
* @param {Array<{field: string, values: unknown[]}>} query IN查询条件
* @returns {Promise<import('chaite').UserState[]>}
*/
async listItemsByInQuery (query) {
await this.ensureInitialized()
if (!query || !query.length) {
return this.listItems()
}
// 只支持userId、nickname、card的过滤
const supportedFields = ['userId', 'nickname', 'card']
const conditions = []
const params = []
for (const item of query) {
if (supportedFields.includes(item.field) && Array.isArray(item.values) && item.values.length > 0) {
const placeholders = item.values.map(() => '?').join(',')
conditions.push(`${item.field} IN (${placeholders})`)
params.push(...item.values)
}
}
if (conditions.length === 0) {
return this.listItems()
}
const whereClause = conditions.join(' AND ')
return new Promise((resolve, reject) => {
this.db.all(`SELECT * FROM ${this.tableName} WHERE ${whereClause}`, params, (err, rows) => {
if (err) {
return reject(err)
}
const userStates = rows.map(row => {
try {
return {
userId: row.userId,
nickname: row.nickname,
card: row.card,
conversations: JSON.parse(row.conversations),
settings: JSON.parse(row.settings),
current: JSON.parse(row.current)
}
} catch (e) {
console.error(`解析用户状态数据错误: ${row.userId}`, e)
return null
}
}).filter(Boolean)
resolve(userStates)
})
})
}
/**
* 清空所有用户状态
* @returns {Promise<void>}
*/
async clear () {
await this.ensureInitialized()
return new Promise((resolve, reject) => {
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
if (err) {
return reject(err)
}
resolve()
})
})
}
/**
* 获取存储名称
* @returns {string}
*/
getName () {
return 'SQLiteUserStateStorage'
}
/**
* 关闭数据库连接
* @returns {Promise<void>}
*/
async close () {
if (!this.db) {
return Promise.resolve()
}
return new Promise((resolve, reject) => {
this.db.close(err => {
if (err) {
reject(err)
} else {
this.initialized = false
this.db = null
resolve()
}
})
})
}
}

View file

@ -0,0 +1,12 @@
import { AbstractUserModeSelector } from 'chaite'
export class ChatGPTUserModeSelector extends AbstractUserModeSelector {
/**
* 根据e判断当前要使用的预设非常灵活
* @param e
* @returns {Promise<import('chaite').ChatPreset>}
*/
getChatPreset (e) {
// todo
}
}

View file

@ -0,0 +1,84 @@
import { LocalIndex } from 'vectra'
import { md5 } from '../../utils/common.js'
/**
* 基于Vectra实现的简单向量数据库作为默认实现
* @implements { import('chaite').VectorDatabase }
*/
export class VectraVectorDatabase {
constructor (indexFile) {
this.index = new LocalIndex(indexFile)
}
async init () {
if (!(await this.index.isIndexCreated())) {
await this.index.createIndex()
}
}
async addVector (vector, text) {
const id = md5(text)
await this.index.insertItem({
vector,
id,
metadata: { text }
})
return id
}
/**
*
* @param vectors
* @param texts
* @returns {Promise<string[]>}
*/
async addVectors (vectors, texts) {
return await Promise.all(vectors.map((v, i) => this.addVector(v, texts[i])))
}
/**
*
* @param queryVector
* @param k
* @returns {Promise<Array<{ id: string, score: number, text: string }>>}
*/
async search (queryVector, k) {
const results = await this.index.queryItems(queryVector, k)
return results.map(r => ({ id: r.item.id, score: r.score, text: r.item.metadata.text }))
}
/**
*
* @param id
* @returns {Promise<{ vector: number[], text: string } | null>}
*/
async getVector (id) {
const result = await this.index.getItem(id)
return {
vector: result.vector,
text: result.metadata.text
}
}
async deleteVector (id) {
await this.index.deleteItem(id)
return true
}
async updateVector (id, newVector, newText) {
await this.index.upsertItem({
id,
vector: newVector,
metadata: { text: newText }
})
return true
}
async count () {
return (await this.index.getIndexStats()).items
}
async clear () {
await this.index.deleteIndex()
}
}

View file

@ -0,0 +1,89 @@
import { Chaite, ChaiteContext, GeminiClient, OpenAIClient } from 'chaite'
async function getIClientByChannel (channel) {
await channel.ready()
const baseLogger = global.logger || console
if (channel.options?.setLogger) {
channel.options.setLogger(baseLogger)
}
const context = new ChaiteContext(baseLogger)
context.setChaite(Chaite.getInstance())
switch (channel.adapterType) {
case 'openai':
return new OpenAIClient(channel.options, context)
case 'gemini':
return new GeminiClient(channel.options, context)
case 'claude':
throw new Error('claude does not support embedding')
default:
throw new Error(`Unsupported adapter ${channel.adapterType}`)
}
}
async function resolveChannelForModel (model) {
const manager = Chaite.getInstance().getChannelsManager()
const channels = await manager.getChannelByModel(model)
if (channels.length === 0) {
throw new Error('No channel found for model: ' + model)
}
return channels[0]
}
export async function getClientForModel (model) {
const channel = await resolveChannelForModel(model)
const client = await getIClientByChannel(channel)
return { client, channel }
}
/**
* 创建一个基于Chaite渠道的向量器
* @param {string} model
* @param {number} dimensions
* @returns {{ textToVector: (text: string) => Promise<number[]>, batchTextToVector: (texts: string[]) => Promise<number[][]> }}
*/
export function createChaiteVectorizer (model, dimensions) {
return {
async textToVector (text) {
const { client } = await getClientForModel(model)
const options = { model }
if (Number.isFinite(dimensions) && dimensions > 0) {
options.dimensions = dimensions
}
const result = await client.getEmbedding(text, options)
return result.embeddings[0]
},
async batchTextToVector (texts) {
const manager = Chaite.getInstance().getChannelsManager()
const channels = await manager.getChannelsByModel(model, texts.length)
if (channels.length === 0) {
throw new Error('No channel found for model: ' + model)
}
const clients = await Promise.all(channels.map(({ channel }) => getIClientByChannel(channel)))
const results = []
let startIndex = 0
for (let i = 0; i < channels.length; i++) {
const { quantity } = channels[i]
const slice = texts.slice(startIndex, startIndex + quantity)
const options = { model }
if (Number.isFinite(dimensions) && dimensions > 0) {
options.dimensions = dimensions
}
const embeddings = await clients[i].getEmbedding(slice, options)
results.push(...embeddings.embeddings)
startIndex += quantity
}
return results
}
}
}
export async function embedTexts (texts, model, dimensions) {
if (!texts || texts.length === 0) {
return []
}
const vectorizer = createChaiteVectorizer(model, dimensions)
if (texts.length === 1) {
return [await vectorizer.textToVector(texts[0])]
}
return await vectorizer.batchTextToVector(texts)
}

633
models/memory/collector.js Normal file
View file

@ -0,0 +1,633 @@
import * as crypto from 'node:crypto'
import ChatGPTConfig from '../../config/config.js'
import { extractGroupFacts } from './extractor.js'
import { memoryService } from './service.js'
import { getBotFramework } from '../../utils/bot.js'
import { ICQQGroupContextCollector, TRSSGroupContextCollector } from '../../utils/group.js'
import { groupHistoryCursorStore } from './groupHistoryCursorStore.js'
const DEFAULT_MAX_WINDOW = 300 // seconds
const DEFAULT_HISTORY_BATCH = 120
const MAX_RECENT_IDS = 200
function nowSeconds () {
return Math.floor(Date.now() / 1000)
}
function normaliseGroupId (groupId) {
return groupId === null || groupId === undefined ? null : String(groupId)
}
function shouldIgnoreMessage (e) {
if (!e || !e.message) {
return true
}
if (e.sender?.user_id && e.sender.user_id === e.bot?.uin) {
return true
}
if (e.isPrivate) {
return true
}
const text = e.msg?.trim()
if (!text) {
return true
}
if (text.startsWith('#')) {
return true
}
const prefix = ChatGPTConfig.basic?.togglePrefix
if (prefix && text.startsWith(prefix)) {
return true
}
return false
}
function extractPlainText (e) {
if (e.msg) {
return e.msg.trim()
}
if (Array.isArray(e.message)) {
return e.message
.filter(item => item.type === 'text')
.map(item => item.text || '')
.join('')
.trim()
}
return ''
}
function extractHistoryText (chat) {
if (!chat) {
return ''
}
if (typeof chat.raw_message === 'string') {
const trimmed = chat.raw_message.trim()
if (trimmed) {
return trimmed
}
}
if (typeof chat.msg === 'string') {
const trimmed = chat.msg.trim()
if (trimmed) {
return trimmed
}
}
if (Array.isArray(chat.message)) {
const merged = chat.message
.filter(item => item && item.type === 'text')
.map(item => item.text || '')
.join('')
.trim()
if (merged) {
return merged
}
}
if (typeof chat.text === 'string') {
const trimmed = chat.text.trim()
if (trimmed) {
return trimmed
}
}
return ''
}
function toPositiveInt (value, fallback = 0) {
const num = Number(value)
if (Number.isFinite(num) && num > 0) {
return Math.floor(num)
}
return fallback
}
function normalizeTimestamp (value) {
if (value === null || value === undefined) {
return 0
}
const num = Number(value)
if (!Number.isFinite(num) || num <= 0) {
return 0
}
if (num > 1e12) {
return Math.floor(num)
}
return Math.floor(num * 1000)
}
function resolveMessageIdCandidate (source) {
if (!source) {
return ''
}
const candidates = [
source.message_id,
source.messageId,
source.msg_id,
source.seq,
source.messageSeq,
source.id
]
for (const candidate of candidates) {
if (candidate || candidate === 0) {
const str = String(candidate).trim()
if (str) {
return str
}
}
}
return ''
}
function resolveUserId (source) {
if (!source) {
return ''
}
const candidates = [
source.user_id,
source.uid,
source.userId,
source.uin,
source.id,
source.qq
]
for (const candidate of candidates) {
if (candidate || candidate === 0) {
const str = String(candidate).trim()
if (str) {
return str
}
}
}
return ''
}
function resolveNickname (source) {
if (!source) {
return ''
}
const candidates = [
source.card,
source.nickname,
source.name,
source.remark
]
for (const candidate of candidates) {
if (typeof candidate === 'string') {
const trimmed = candidate.trim()
if (trimmed) {
return trimmed
}
}
}
return ''
}
export class GroupMessageCollector {
constructor () {
this.buffers = new Map()
this.processing = new Set()
this.groupStates = new Map()
this.lastPollAt = 0
this.polling = false
this.selfIds = null
}
get groupConfig () {
return ChatGPTConfig.memory?.group || {}
}
get historyBatchSize () {
const config = this.groupConfig
const configured = toPositiveInt(config.historyBatchSize, 0)
if (configured > 0) {
return configured
}
const minCount = toPositiveInt(config.minMessageCount, 80)
return Math.max(minCount, DEFAULT_HISTORY_BATCH)
}
get historyPollIntervalMs () {
const config = this.groupConfig
const configured = Number(config.historyPollInterval)
if (Number.isFinite(configured) && configured > 0) {
return Math.floor(configured) * 1000
}
if (configured === 0) {
return 0
}
const fallbackSeconds = Math.max(toPositiveInt(config.maxMessageWindow, DEFAULT_MAX_WINDOW), DEFAULT_MAX_WINDOW)
return fallbackSeconds * 1000
}
async tickHistoryPolling (force = false) {
const intervalMs = this.historyPollIntervalMs
if (intervalMs <= 0) {
return
}
if (!force) {
const now = Date.now()
if (this.lastPollAt && (now - this.lastPollAt) < intervalMs) {
return
}
} else {
this.refreshSelfIds()
}
await this.runHistoryPoll()
}
async runHistoryPoll () {
if (this.polling) {
return
}
this.polling = true
try {
logger.info('[Memory] start group history poll')
await this.pollGroupHistories()
} catch (err) {
logger.error('[Memory] group history poll execution failed:', err)
} finally {
this.lastPollAt = Date.now()
this.polling = false
}
}
async pollGroupHistories () {
const config = this.groupConfig
if (!config.enable) {
return
}
const groupIds = (config.enabledGroups || [])
.map(normaliseGroupId)
.filter(Boolean)
if (groupIds.length === 0) {
return
}
this.refreshSelfIds()
const framework = getBotFramework()
for (const groupId of groupIds) {
if (!memoryService.isGroupMemoryEnabled(groupId)) {
continue
}
const collector = framework === 'trss'
? new TRSSGroupContextCollector()
: new ICQQGroupContextCollector()
try {
const added = await this.collectHistoryForGroup(collector, groupId)
if (added > 0) {
logger.debug(`[Memory] history poll buffered ${added} messages, group=${groupId}`)
}
} catch (err) {
logger.warn(`[Memory] failed to poll history for group=${groupId}:`, err)
}
}
}
async collectHistoryForGroup (collector, groupId) {
const limit = this.historyBatchSize
if (!limit) {
return 0
}
let chats = []
try {
chats = await collector.collect(undefined, groupId, 0, limit)
} catch (err) {
logger.warn(`[Memory] failed to collect history for group=${groupId}:`, err)
return 0
}
if (!Array.isArray(chats) || chats.length === 0) {
return 0
}
const messages = []
for (const chat of chats) {
const payload = this.transformHistoryMessage(groupId, chat)
if (payload) {
messages.push(payload)
}
}
if (!messages.length) {
return 0
}
messages.sort((a, b) => normalizeTimestamp(a.timestamp) - normalizeTimestamp(b.timestamp))
let queued = 0
for (const payload of messages) {
if (this.queueMessage(groupId, payload)) {
queued++
}
}
return queued
}
transformHistoryMessage (groupId, chat) {
const text = extractHistoryText(chat)
if (!text) {
return null
}
if (text.startsWith('#')) {
return null
}
const prefix = ChatGPTConfig.basic?.togglePrefix
if (prefix && text.startsWith(prefix)) {
return null
}
const sender = chat?.sender || {}
const userId = resolveUserId(sender) || resolveUserId(chat)
if (this.isBotSelfId(userId)) {
return null
}
return {
message_id: resolveMessageIdCandidate(chat),
user_id: userId,
nickname: resolveNickname(sender) || resolveNickname(chat),
text,
timestamp: chat?.time ?? chat?.timestamp ?? chat?.message_time ?? Date.now()
}
}
queueMessage (groupId, rawPayload) {
if (!rawPayload || !rawPayload.text) {
return false
}
const state = this.getGroupState(groupId)
const messageId = this.ensureMessageId(rawPayload)
const timestampMs = normalizeTimestamp(rawPayload.timestamp)
const buffer = this.getBuffer(groupId)
const payload = {
message_id: messageId,
user_id: rawPayload.user_id ? String(rawPayload.user_id) : '',
nickname: rawPayload.nickname ? String(rawPayload.nickname) : '',
text: rawPayload.text,
timestamp: timestampMs || Date.now()
}
const messageKey = this.resolveMessageKey(payload, messageId, timestampMs)
if (this.shouldSkipMessage(state, timestampMs, messageKey, payload.message_id)) {
return false
}
this.updateGroupState(groupId, state, timestampMs, messageKey, payload.message_id)
buffer.messages.push(payload)
logger.debug(`[Memory] buffered group message, group=${groupId}, buffer=${buffer.messages.length}`)
this.tryTriggerFlush(groupId, buffer)
return true
}
ensureMessageId (payload) {
const direct = payload?.message_id ? String(payload.message_id).trim() : ''
if (direct) {
return direct
}
const fallback = resolveMessageIdCandidate(payload)
if (fallback) {
return fallback
}
return crypto.randomUUID()
}
resolveMessageKey (payload, messageId, timestampMs) {
if (messageId) {
return messageId
}
const parts = [
timestampMs || '',
payload?.user_id || '',
(payload?.text || '').slice(0, 32)
]
return parts.filter(Boolean).join(':')
}
getGroupState (groupId) {
let state = this.groupStates.get(groupId)
if (!state) {
const cursor = groupHistoryCursorStore.getCursor(groupId)
const lastTimestamp = Number(cursor?.last_timestamp) || 0
const lastMessageId = cursor?.last_message_id || null
state = {
lastTimestamp,
lastMessageId,
recentIds: new Set()
}
if (lastMessageId) {
state.recentIds.add(lastMessageId)
}
this.groupStates.set(groupId, state)
}
return state
}
shouldSkipMessage (state, timestampMs, messageKey, messageId) {
if (!state) {
return false
}
if (messageId && state.lastMessageId && messageId === state.lastMessageId) {
return true
}
if (timestampMs && timestampMs < state.lastTimestamp) {
return true
}
if (timestampMs && timestampMs === state.lastTimestamp && messageKey && state.recentIds.has(messageKey)) {
return true
}
if (!timestampMs && messageKey && state.recentIds.has(messageKey)) {
return true
}
return false
}
updateGroupState (groupId, state, timestampMs, messageKey, messageId) {
const hasTimestamp = Number.isFinite(timestampMs) && timestampMs > 0
if (!hasTimestamp) {
if (messageKey) {
state.recentIds.add(messageKey)
if (state.recentIds.size > MAX_RECENT_IDS) {
const ids = Array.from(state.recentIds).slice(-MAX_RECENT_IDS)
state.recentIds = new Set(ids)
}
}
if (messageId) {
state.lastMessageId = String(messageId)
groupHistoryCursorStore.updateCursor(groupId, {
lastMessageId: state.lastMessageId,
lastTimestamp: state.lastTimestamp || null
})
}
return
}
if (timestampMs > state.lastTimestamp) {
state.lastTimestamp = timestampMs
state.recentIds = messageKey ? new Set([messageKey]) : new Set()
} else if (timestampMs === state.lastTimestamp && messageKey) {
state.recentIds.add(messageKey)
if (state.recentIds.size > MAX_RECENT_IDS) {
const ids = Array.from(state.recentIds).slice(-MAX_RECENT_IDS)
state.recentIds = new Set(ids)
}
}
if (messageId) {
state.lastMessageId = String(messageId)
}
groupHistoryCursorStore.updateCursor(groupId, {
lastMessageId: state.lastMessageId || null,
lastTimestamp: state.lastTimestamp || timestampMs
})
}
getBuffer (groupId) {
let buffer = this.buffers.get(groupId)
if (!buffer) {
buffer = {
messages: [],
lastFlushAt: nowSeconds()
}
this.buffers.set(groupId, buffer)
}
return buffer
}
tryTriggerFlush (groupId, buffer) {
const config = this.groupConfig
const minCount = config.minMessageCount || 50
const maxWindow = config.maxMessageWindow || DEFAULT_MAX_WINDOW
const shouldFlushByCount = buffer.messages.length >= minCount
const shouldFlushByTime = buffer.messages.length > 0 && (nowSeconds() - buffer.lastFlushAt) >= maxWindow
logger.debug(`[Memory] try trigger flush, group=${groupId}, count=${buffer.messages.length}, lastFlushAt=${buffer.lastFlushAt}, shouldFlushByCount=${shouldFlushByCount}, shouldFlushByTime=${shouldFlushByTime}`)
if (shouldFlushByCount || shouldFlushByTime) {
logger.info(`[Memory] trigger group fact extraction, group=${groupId}, count=${buffer.messages.length}, reason=${shouldFlushByCount ? 'count' : 'timeout'}`)
this.flush(groupId).catch(err => logger.error('Failed to flush group memory:', err))
}
}
push (e) {
const groupId = normaliseGroupId(e.group_id || e.group?.group_id)
if (!memoryService.isGroupMemoryEnabled(groupId)) {
return
}
if (shouldIgnoreMessage(e)) {
return
}
const text = extractPlainText(e)
if (!text) {
return
}
this.addSelfId(e.bot?.uin)
const messageId = e.message_id || e.seq || crypto.randomUUID()
logger.debug(`[Memory] collect group message, group=${groupId}, user=${e.sender?.user_id}, buffer=${(this.buffers.get(groupId)?.messages.length || 0) + 1}`)
this.queueMessage(groupId, {
message_id: messageId,
user_id: String(e.sender?.user_id || ''),
nickname: e.sender?.card || e.sender?.nickname || '',
text,
timestamp: e.time || Date.now()
})
}
async flush (groupId) {
if (this.processing.has(groupId)) {
return
}
const buffer = this.buffers.get(groupId)
if (!buffer || buffer.messages.length === 0) {
return
}
this.processing.add(groupId)
try {
const messages = buffer.messages
this.buffers.set(groupId, {
messages: [],
lastFlushAt: nowSeconds()
})
logger.debug(`[Memory] flushing group buffer, group=${groupId}, messages=${messages.length}`)
const simplified = messages.map(msg => ({
message_id: msg.message_id,
user_id: msg.user_id,
nickname: msg.nickname,
text: msg.text
}))
const factCandidates = await extractGroupFacts(simplified)
if (factCandidates.length === 0) {
logger.debug(`[Memory] group fact extraction returned empty, group=${groupId}`)
return
}
const messageMap = new Map(messages.map(msg => [msg.message_id, msg.text]))
const enrichedFacts = factCandidates.map(fact => {
if (!fact.source_message_ids && fact.sourceMessages) {
fact.source_message_ids = fact.sourceMessages
}
let ids = []
if (Array.isArray(fact.source_message_ids)) {
ids = fact.source_message_ids.map(id => String(id))
} else if (typeof fact.source_message_ids === 'string') {
ids = fact.source_message_ids.split(',').map(id => id.trim()).filter(Boolean)
}
if (!fact.source_messages && ids.length > 0) {
const summary = ids
.map(id => messageMap.get(id) || '')
.filter(Boolean)
.join('\n')
fact.source_messages = summary
}
fact.source_message_ids = ids
if (!fact.involved_users || !Array.isArray(fact.involved_users)) {
fact.involved_users = []
} else {
fact.involved_users = fact.involved_users.map(id => String(id))
}
return fact
})
const saved = await memoryService.saveGroupFacts(groupId, enrichedFacts)
logger.info(`[Memory] saved ${saved.length} group facts for group=${groupId}`)
} finally {
this.processing.delete(groupId)
}
}
addSelfId (uin) {
if (uin === null || uin === undefined) {
return
}
const str = String(uin)
if (!str) {
return
}
if (!this.selfIds) {
this.selfIds = new Set()
}
this.selfIds.add(str)
}
refreshSelfIds () {
this.selfIds = this.collectSelfIds()
}
collectSelfIds () {
const ids = new Set()
try {
const botGlobal = global.Bot
if (botGlobal?.bots && typeof botGlobal.bots === 'object') {
for (const bot of Object.values(botGlobal.bots)) {
if (bot?.uin) {
ids.add(String(bot.uin))
}
}
}
if (botGlobal?.uin) {
ids.add(String(botGlobal.uin))
}
} catch (err) {
logger?.debug?.('[Memory] failed to collect bot self ids: %o', err)
}
return ids
}
isBotSelfId (userId) {
if (userId === null || userId === undefined) {
return false
}
const str = String(userId)
if (!str) {
return false
}
if (!this.selfIds || this.selfIds.size === 0) {
this.refreshSelfIds()
}
return this.selfIds?.has(str) || false
}
}

755
models/memory/database.js Normal file
View file

@ -0,0 +1,755 @@
import Database from 'better-sqlite3'
import * as sqliteVec from 'sqlite-vec'
import fs from 'fs'
import path from 'path'
import ChatGPTConfig from '../../config/config.js'
const META_VECTOR_DIM_KEY = 'group_vec_dimension'
const META_VECTOR_MODEL_KEY = 'group_vec_model'
const META_GROUP_TOKENIZER_KEY = 'group_memory_tokenizer'
const META_USER_TOKENIZER_KEY = 'user_memory_tokenizer'
const TOKENIZER_DEFAULT = 'unicode61'
const SIMPLE_MATCH_SIMPLE = 'simple_query'
const SIMPLE_MATCH_JIEBA = 'jieba_query'
const PLUGIN_ROOT = path.resolve('./plugins/chatgpt-plugin')
let dbInstance = null
let cachedVectorDimension = null
let cachedVectorModel = null
let userMemoryFtsConfig = {
tokenizer: TOKENIZER_DEFAULT,
matchQuery: null
}
let groupMemoryFtsConfig = {
tokenizer: TOKENIZER_DEFAULT,
matchQuery: null
}
const simpleExtensionState = {
requested: false,
enabled: false,
loaded: false,
error: null,
libraryPath: '',
dictPath: '',
tokenizer: TOKENIZER_DEFAULT,
matchQuery: null
}
function resolveDbPath () {
const relativePath = ChatGPTConfig.memory?.database || 'data/memory.db'
return path.resolve('./plugins/chatgpt-plugin', relativePath)
}
export function resolvePluginPath (targetPath) {
if (!targetPath) {
return ''
}
if (path.isAbsolute(targetPath)) {
return targetPath
}
return path.resolve(PLUGIN_ROOT, targetPath)
}
export function toPluginRelativePath (absolutePath) {
if (!absolutePath) {
return ''
}
return path.relative(PLUGIN_ROOT, absolutePath)
}
function resolvePreferredDimension () {
const { memory, llm } = ChatGPTConfig
if (memory?.vectorDimensions && memory.vectorDimensions > 0) {
return memory.vectorDimensions
}
if (llm?.dimensions && llm.dimensions > 0) {
return llm.dimensions
}
return 1536
}
function ensureDirectory (filePath) {
const dir = path.dirname(filePath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
}
function ensureMetaTable (db) {
db.exec(`
CREATE TABLE IF NOT EXISTS memory_meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)
`)
}
function getMetaValue (db, key) {
const stmt = db.prepare('SELECT value FROM memory_meta WHERE key = ?')
const row = stmt.get(key)
return row ? row.value : null
}
function setMetaValue (db, key, value) {
db.prepare(`
INSERT INTO memory_meta (key, value)
VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value
`).run(key, value)
}
function resetSimpleState (overrides = {}) {
simpleExtensionState.loaded = false
simpleExtensionState.error = null
simpleExtensionState.tokenizer = TOKENIZER_DEFAULT
simpleExtensionState.matchQuery = null
Object.assign(simpleExtensionState, overrides)
userMemoryFtsConfig = {
tokenizer: TOKENIZER_DEFAULT,
matchQuery: null
}
groupMemoryFtsConfig = {
tokenizer: TOKENIZER_DEFAULT,
matchQuery: null
}
}
function sanitiseRawFtsInput (input) {
if (!input) {
return ''
}
const trimmed = String(input).trim()
if (!trimmed) {
return ''
}
const replaced = trimmed
.replace(/["'`]+/g, ' ')
.replace(/\u3000/g, ' ')
.replace(/[^\p{L}\p{N}\u4E00-\u9FFF\u3040-\u30FF\uAC00-\uD7AF\u1100-\u11FF\s]+/gu, ' ')
const collapsed = replaced.replace(/\s+/g, ' ').trim()
return collapsed || trimmed
}
function isSimpleLibraryFile (filename) {
return /(^libsimple.*\.(so|dylib|dll)$)|(^simple\.(so|dylib|dll)$)/i.test(filename)
}
function findSimpleLibrary (startDir) {
const stack = [startDir]
while (stack.length > 0) {
const dir = stack.pop()
if (!dir || !fs.existsSync(dir)) {
continue
}
const entries = fs.readdirSync(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
stack.push(fullPath)
} else if (entry.isFile() && isSimpleLibraryFile(entry.name)) {
return fullPath
}
}
}
return ''
}
function locateDictPathNear (filePath) {
if (!filePath) {
return ''
}
let currentDir = path.dirname(filePath)
for (let depth = 0; depth < 5 && currentDir && currentDir !== path.dirname(currentDir); depth++) {
const dictCandidate = path.join(currentDir, 'dict')
if (fs.existsSync(dictCandidate) && fs.statSync(dictCandidate).isDirectory()) {
return dictCandidate
}
currentDir = path.dirname(currentDir)
}
return ''
}
function discoverSimplePaths () {
const searchRoots = [
path.join(PLUGIN_ROOT, 'resources/simple'),
path.join(PLUGIN_ROOT, 'resources'),
path.join(PLUGIN_ROOT, 'lib/simple'),
PLUGIN_ROOT
]
for (const root of searchRoots) {
if (!root || !fs.existsSync(root)) {
continue
}
const lib = findSimpleLibrary(root)
if (lib) {
const dictCandidate = locateDictPathNear(lib)
return {
libraryPath: toPluginRelativePath(lib) || lib,
dictPath: dictCandidate ? (toPluginRelativePath(dictCandidate) || dictCandidate) : ''
}
}
}
return { libraryPath: '', dictPath: '' }
}
function applySimpleExtension (db) {
const config = ChatGPTConfig.memory?.extensions?.simple || {}
simpleExtensionState.requested = Boolean(config.enable)
simpleExtensionState.enabled = Boolean(config.enable)
simpleExtensionState.libraryPath = config.libraryPath || ''
simpleExtensionState.dictPath = config.dictPath || ''
if (!config.enable) {
logger?.debug?.('[Memory] simple tokenizer disabled via config')
resetSimpleState({ requested: false, enabled: false })
return
}
if (!simpleExtensionState.libraryPath) {
const detected = discoverSimplePaths()
if (detected.libraryPath) {
simpleExtensionState.libraryPath = detected.libraryPath
simpleExtensionState.dictPath = detected.dictPath
config.libraryPath = detected.libraryPath
if (detected.dictPath) {
config.dictPath = detected.dictPath
}
}
}
const resolvedLibraryPath = resolvePluginPath(config.libraryPath)
if (!resolvedLibraryPath || !fs.existsSync(resolvedLibraryPath)) {
logger?.warn?.('[Memory] simple tokenizer library missing:', resolvedLibraryPath || '(empty path)')
resetSimpleState({
requested: true,
enabled: true,
error: `Simple extension library not found at ${resolvedLibraryPath || '(empty path)'}`
})
return
}
try {
logger?.info?.('[Memory] loading simple tokenizer extension from', resolvedLibraryPath)
db.loadExtension(resolvedLibraryPath)
if (config.useJieba) {
const resolvedDict = resolvePluginPath(config.dictPath)
if (resolvedDict && fs.existsSync(resolvedDict)) {
try {
logger?.debug?.('[Memory] configuring simple tokenizer jieba dict:', resolvedDict)
db.prepare('select jieba_dict(?)').get(resolvedDict)
} catch (err) {
logger?.warn?.('Failed to register jieba dict for simple extension:', err)
}
} else {
logger?.warn?.('Simple extension jieba dict path missing:', resolvedDict)
}
}
const tokenizer = config.useJieba ? 'simple_jieba' : 'simple'
const matchQuery = config.useJieba ? SIMPLE_MATCH_JIEBA : SIMPLE_MATCH_SIMPLE
simpleExtensionState.loaded = true
simpleExtensionState.error = null
simpleExtensionState.tokenizer = tokenizer
simpleExtensionState.matchQuery = matchQuery
logger?.info?.('[Memory] simple tokenizer initialised, tokenizer=%s, matchQuery=%s', tokenizer, matchQuery)
userMemoryFtsConfig = {
tokenizer,
matchQuery
}
groupMemoryFtsConfig = {
tokenizer,
matchQuery
}
return
} catch (error) {
logger?.error?.('Failed to load simple extension:', error)
resetSimpleState({
requested: true,
enabled: true,
error: `Failed to load simple extension: ${error?.message || error}`
})
}
}
function loadSimpleExtensionForCleanup (db) {
if (!ChatGPTConfig.memory.extensions) {
ChatGPTConfig.memory.extensions = {}
}
if (!ChatGPTConfig.memory.extensions.simple) {
ChatGPTConfig.memory.extensions.simple = {
enable: false,
libraryPath: '',
dictPath: '',
useJieba: false
}
}
const config = ChatGPTConfig.memory.extensions.simple
let libraryPath = config.libraryPath || ''
let dictPath = config.dictPath || ''
if (!libraryPath) {
const detected = discoverSimplePaths()
libraryPath = detected.libraryPath
if (detected.dictPath && !dictPath) {
dictPath = detected.dictPath
}
if (libraryPath) {
ChatGPTConfig.memory.extensions.simple = ChatGPTConfig.memory.extensions.simple || {}
ChatGPTConfig.memory.extensions.simple.libraryPath = libraryPath
if (dictPath) {
ChatGPTConfig.memory.extensions.simple.dictPath = dictPath
}
}
}
const resolvedLibraryPath = resolvePluginPath(libraryPath)
if (!resolvedLibraryPath || !fs.existsSync(resolvedLibraryPath)) {
logger?.warn?.('[Memory] cleanup requires simple extension but library missing:', resolvedLibraryPath || '(empty path)')
return false
}
try {
logger?.info?.('[Memory] temporarily loading simple extension for cleanup tasks')
db.loadExtension(resolvedLibraryPath)
const useJieba = Boolean(config.useJieba)
if (useJieba) {
const resolvedDict = resolvePluginPath(dictPath)
if (resolvedDict && fs.existsSync(resolvedDict)) {
try {
db.prepare('select jieba_dict(?)').get(resolvedDict)
} catch (err) {
logger?.warn?.('Failed to set jieba dict during cleanup:', err)
}
}
}
return true
} catch (error) {
logger?.error?.('Failed to load simple extension for cleanup:', error)
return false
}
}
function ensureGroupFactsTable (db) {
ensureMetaTable(db)
db.exec(`
CREATE TABLE IF NOT EXISTS group_facts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
group_id TEXT NOT NULL,
fact TEXT NOT NULL,
topic TEXT,
importance REAL DEFAULT 0.5,
source_message_ids TEXT,
source_messages TEXT,
involved_users TEXT,
created_at TEXT DEFAULT (datetime('now'))
)
`)
db.exec(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_group_facts_unique
ON group_facts(group_id, fact)
`)
db.exec(`
CREATE INDEX IF NOT EXISTS idx_group_facts_group
ON group_facts(group_id, importance DESC, created_at DESC)
`)
ensureGroupFactsFtsTable(db)
}
function ensureGroupHistoryCursorTable (db) {
ensureMetaTable(db)
db.exec(`
CREATE TABLE IF NOT EXISTS group_history_cursor (
group_id TEXT PRIMARY KEY,
last_message_id TEXT,
last_timestamp INTEGER
)
`)
}
function ensureUserMemoryTable (db) {
ensureMetaTable(db)
db.exec(`
CREATE TABLE IF NOT EXISTS user_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
group_id TEXT,
key TEXT NOT NULL,
value TEXT NOT NULL,
importance REAL DEFAULT 0.5,
source_message_id TEXT,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
)
`)
db.exec(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_memory_key
ON user_memory(user_id, coalesce(group_id, ''), key)
`)
db.exec(`
CREATE INDEX IF NOT EXISTS idx_user_memory_group
ON user_memory(group_id)
`)
db.exec(`
CREATE INDEX IF NOT EXISTS idx_user_memory_user
ON user_memory(user_id)
`)
ensureUserMemoryFtsTable(db)
}
function dropGroupFactsFtsArtifacts (db) {
try {
db.exec(`
DROP TRIGGER IF EXISTS group_facts_ai;
DROP TRIGGER IF EXISTS group_facts_ad;
DROP TRIGGER IF EXISTS group_facts_au;
DROP TABLE IF EXISTS group_facts_fts;
`)
} catch (err) {
if (String(err?.message || '').includes('no such tokenizer')) {
const loaded = loadSimpleExtensionForCleanup(db)
if (loaded) {
db.exec(`
DROP TRIGGER IF EXISTS group_facts_ai;
DROP TRIGGER IF EXISTS group_facts_ad;
DROP TRIGGER IF EXISTS group_facts_au;
DROP TABLE IF EXISTS group_facts_fts;
`)
} else {
logger?.warn?.('[Memory] Falling back to raw schema cleanup for group_facts_fts')
try {
db.exec('PRAGMA writable_schema = ON;')
db.exec(`DELETE FROM sqlite_master WHERE name IN ('group_facts_ai','group_facts_ad','group_facts_au','group_facts_fts');`)
} finally {
db.exec('PRAGMA writable_schema = OFF;')
}
}
} else {
throw err
}
}
}
function createGroupFactsFts (db, tokenizer) {
logger?.info?.('[Memory] creating group_facts_fts with tokenizer=%s', tokenizer)
db.exec(`
CREATE VIRTUAL TABLE group_facts_fts
USING fts5(
fact,
topic,
content = 'group_facts',
content_rowid = 'id',
tokenize = '${tokenizer}'
)
`)
db.exec(`
CREATE TRIGGER group_facts_ai AFTER INSERT ON group_facts BEGIN
INSERT INTO group_facts_fts(rowid, fact, topic)
VALUES (new.id, new.fact, coalesce(new.topic, ''));
END;
`)
db.exec(`
CREATE TRIGGER group_facts_ad AFTER DELETE ON group_facts BEGIN
INSERT INTO group_facts_fts(group_facts_fts, rowid, fact, topic)
VALUES ('delete', old.id, old.fact, coalesce(old.topic, ''));
END;
`)
db.exec(`
CREATE TRIGGER group_facts_au AFTER UPDATE ON group_facts BEGIN
INSERT INTO group_facts_fts(group_facts_fts, rowid, fact, topic)
VALUES ('delete', old.id, old.fact, coalesce(old.topic, ''));
INSERT INTO group_facts_fts(rowid, fact, topic)
VALUES (new.id, new.fact, coalesce(new.topic, ''));
END;
`)
try {
db.exec(`INSERT INTO group_facts_fts(group_facts_fts) VALUES ('rebuild')`)
} catch (err) {
logger?.debug?.('Group facts FTS rebuild skipped:', err?.message || err)
}
}
function ensureGroupFactsFtsTable (db) {
const desiredTokenizer = groupMemoryFtsConfig.tokenizer || TOKENIZER_DEFAULT
const storedTokenizer = getMetaValue(db, META_GROUP_TOKENIZER_KEY)
const tableExists = db.prepare(`
SELECT name FROM sqlite_master
WHERE type = 'table' AND name = 'group_facts_fts'
`).get()
if (storedTokenizer && storedTokenizer !== desiredTokenizer) {
dropGroupFactsFtsArtifacts(db)
} else if (!storedTokenizer && tableExists) {
// Unknown tokenizer, drop to ensure consistency.
dropGroupFactsFtsArtifacts(db)
}
const existsAfterDrop = db.prepare(`
SELECT name FROM sqlite_master
WHERE type = 'table' AND name = 'group_facts_fts'
`).get()
if (!existsAfterDrop) {
createGroupFactsFts(db, desiredTokenizer)
setMetaValue(db, META_GROUP_TOKENIZER_KEY, desiredTokenizer)
logger?.info?.('[Memory] group facts FTS initialised with tokenizer=%s', desiredTokenizer)
}
}
function dropUserMemoryFtsArtifacts (db) {
try {
db.exec(`
DROP TRIGGER IF EXISTS user_memory_ai;
DROP TRIGGER IF EXISTS user_memory_ad;
DROP TRIGGER IF EXISTS user_memory_au;
DROP TABLE IF EXISTS user_memory_fts;
`)
} catch (err) {
if (String(err?.message || '').includes('no such tokenizer')) {
const loaded = loadSimpleExtensionForCleanup(db)
if (loaded) {
db.exec(`
DROP TRIGGER IF EXISTS user_memory_ai;
DROP TRIGGER IF EXISTS user_memory_ad;
DROP TRIGGER IF EXISTS user_memory_au;
DROP TABLE IF EXISTS user_memory_fts;
`)
} else {
logger?.warn?.('[Memory] Falling back to raw schema cleanup for user_memory_fts')
try {
db.exec('PRAGMA writable_schema = ON;')
db.exec(`DELETE FROM sqlite_master WHERE name IN ('user_memory_ai','user_memory_ad','user_memory_au','user_memory_fts');`)
} finally {
db.exec('PRAGMA writable_schema = OFF;')
}
}
} else {
throw err
}
}
}
function createUserMemoryFts (db, tokenizer) {
logger?.info?.('[Memory] creating user_memory_fts with tokenizer=%s', tokenizer)
db.exec(`
CREATE VIRTUAL TABLE user_memory_fts
USING fts5(
value,
content = 'user_memory',
content_rowid = 'id',
tokenize = '${tokenizer}'
)
`)
db.exec(`
CREATE TRIGGER user_memory_ai AFTER INSERT ON user_memory BEGIN
INSERT INTO user_memory_fts(rowid, value)
VALUES (new.id, new.value);
END;
`)
db.exec(`
CREATE TRIGGER user_memory_ad AFTER DELETE ON user_memory BEGIN
INSERT INTO user_memory_fts(user_memory_fts, rowid, value)
VALUES ('delete', old.id, old.value);
END;
`)
db.exec(`
CREATE TRIGGER user_memory_au AFTER UPDATE ON user_memory BEGIN
INSERT INTO user_memory_fts(user_memory_fts, rowid, value)
VALUES ('delete', old.id, old.value);
INSERT INTO user_memory_fts(rowid, value)
VALUES (new.id, new.value);
END;
`)
try {
db.exec(`INSERT INTO user_memory_fts(user_memory_fts) VALUES ('rebuild')`)
} catch (err) {
logger?.debug?.('User memory FTS rebuild skipped:', err?.message || err)
}
}
function ensureUserMemoryFtsTable (db) {
const desiredTokenizer = userMemoryFtsConfig.tokenizer || TOKENIZER_DEFAULT
const storedTokenizer = getMetaValue(db, META_USER_TOKENIZER_KEY)
const tableExists = db.prepare(`
SELECT name FROM sqlite_master
WHERE type = 'table' AND name = 'user_memory_fts'
`).get()
if (storedTokenizer && storedTokenizer !== desiredTokenizer) {
dropUserMemoryFtsArtifacts(db)
} else if (!storedTokenizer && tableExists) {
dropUserMemoryFtsArtifacts(db)
}
const existsAfterDrop = db.prepare(`
SELECT name FROM sqlite_master
WHERE type = 'table' AND name = 'user_memory_fts'
`).get()
if (!existsAfterDrop) {
createUserMemoryFts(db, desiredTokenizer)
setMetaValue(db, META_USER_TOKENIZER_KEY, desiredTokenizer)
logger?.info?.('[Memory] user memory FTS initialised with tokenizer=%s', desiredTokenizer)
}
}
function createVectorTable (db, dimension) {
if (!dimension || dimension <= 0) {
throw new Error(`Invalid vector dimension for table creation: ${dimension}`)
}
db.exec(`CREATE VIRTUAL TABLE vec_group_facts USING vec0(embedding float[${dimension}])`)
}
function ensureVectorTable (db) {
ensureMetaTable(db)
if (cachedVectorDimension !== null) {
return cachedVectorDimension
}
const preferredDimension = resolvePreferredDimension()
const stored = getMetaValue(db, META_VECTOR_DIM_KEY)
const storedModel = getMetaValue(db, META_VECTOR_MODEL_KEY)
const currentModel = ChatGPTConfig.llm?.embeddingModel || ''
const tableExists = Boolean(db.prepare(`
SELECT name FROM sqlite_master
WHERE type = 'table' AND name = 'vec_group_facts'
`).get())
const parseDimension = value => {
if (!value && value !== 0) return 0
const parsed = parseInt(String(value), 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0
}
const storedDimension = parseDimension(stored)
let dimension = storedDimension
let tablePresent = tableExists
let needsTableReset = false
if (tableExists && storedDimension <= 0) {
needsTableReset = true
}
if (needsTableReset && tableExists) {
try {
db.exec('DROP TABLE IF EXISTS vec_group_facts')
tablePresent = false
dimension = 0
} catch (err) {
logger?.warn?.('[Memory] failed to drop vec_group_facts during dimension change:', err)
}
}
if (!tablePresent) {
if (dimension <= 0) {
dimension = parseDimension(preferredDimension)
}
if (dimension > 0) {
try {
createVectorTable(db, dimension)
tablePresent = true
setMetaValue(db, META_VECTOR_MODEL_KEY, currentModel)
setMetaValue(db, META_VECTOR_DIM_KEY, String(dimension))
cachedVectorDimension = dimension
cachedVectorModel = currentModel
return cachedVectorDimension
} catch (err) {
logger?.error?.('[Memory] failed to (re)create vec_group_facts table:', err)
dimension = 0
}
}
}
if (tablePresent && storedDimension > 0) {
cachedVectorDimension = storedDimension
cachedVectorModel = storedModel || currentModel
return cachedVectorDimension
}
// At this point we failed to determine a valid dimension, set metadata to 0 to avoid loops.
setMetaValue(db, META_VECTOR_MODEL_KEY, currentModel)
setMetaValue(db, META_VECTOR_DIM_KEY, '0')
cachedVectorDimension = 0
cachedVectorModel = currentModel
return cachedVectorDimension
}
export function resetVectorTableDimension (dimension) {
if (!Number.isFinite(dimension) || dimension <= 0) {
throw new Error(`Invalid vector dimension: ${dimension}`)
}
const db = getMemoryDatabase()
try {
db.exec('DROP TABLE IF EXISTS vec_group_facts')
} catch (err) {
logger?.warn?.('[Memory] failed to drop vec_group_facts:', err)
}
createVectorTable(db, dimension)
setMetaValue(db, META_VECTOR_DIM_KEY, dimension.toString())
const model = ChatGPTConfig.llm?.embeddingModel || ''
setMetaValue(db, META_VECTOR_MODEL_KEY, model)
cachedVectorDimension = dimension
cachedVectorModel = model
}
function migrate (db) {
ensureGroupFactsTable(db)
ensureGroupHistoryCursorTable(db)
ensureUserMemoryTable(db)
ensureVectorTable(db)
}
export function getUserMemoryFtsConfig () {
return { ...userMemoryFtsConfig }
}
export function getGroupMemoryFtsConfig () {
return { ...groupMemoryFtsConfig }
}
export function getSimpleExtensionState () {
return { ...simpleExtensionState }
}
export function sanitiseFtsQueryInput (query, ftsConfig) {
if (!query) {
return ''
}
if (ftsConfig?.matchQuery) {
return String(query).trim()
}
return sanitiseRawFtsInput(query)
}
export function getMemoryDatabase () {
if (dbInstance) {
return dbInstance
}
const dbPath = resolveDbPath()
ensureDirectory(dbPath)
logger?.info?.('[Memory] opening memory database at %s', dbPath)
dbInstance = new Database(dbPath)
sqliteVec.load(dbInstance)
resetSimpleState({
requested: false,
enabled: false
})
applySimpleExtension(dbInstance)
migrate(dbInstance)
logger?.info?.('[Memory] memory database init completed (simple loaded=%s)', simpleExtensionState.loaded)
return dbInstance
}
export function getVectorDimension () {
const currentModel = ChatGPTConfig.llm?.embeddingModel || ''
if (cachedVectorModel && cachedVectorModel !== currentModel) {
cachedVectorDimension = null
cachedVectorModel = null
}
if (cachedVectorDimension !== null) {
return cachedVectorDimension
}
const db = getMemoryDatabase()
return ensureVectorTable(db)
}
export function resetCachedDimension () {
cachedVectorDimension = null
cachedVectorModel = null
}
export function resetMemoryDatabaseInstance () {
if (dbInstance) {
try {
dbInstance.close()
} catch (error) {
console.warn('Failed to close memory database:', error)
}
}
dbInstance = null
cachedVectorDimension = null
cachedVectorModel = null
}

306
models/memory/extractor.js Normal file
View file

@ -0,0 +1,306 @@
import { SendMessageOption, Chaite } from 'chaite'
import ChatGPTConfig from '../../config/config.js'
import { getClientForModel } from '../chaite/vectorizer.js'
function collectTextFromResponse (response) {
if (!response?.contents) {
return ''
}
return response.contents
.filter(content => content.type === 'text')
.map(content => content.text || '')
.join('\n')
.trim()
}
function parseJSON (text) {
if (!text) {
return null
}
const trimmed = text.trim()
const codeBlockMatch = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i)
const payload = codeBlockMatch ? codeBlockMatch[1] : trimmed
try {
return JSON.parse(payload)
} catch (err) {
logger.warn('Failed to parse JSON from memory extractor response:', text)
return null
}
}
function formatEntry (entry) {
let str = ''
try {
if (typeof entry === 'string') {
str = entry
} else {
str = JSON.stringify(entry)
}
} catch (err) {
str = String(entry)
}
const limit = 200
return str.length > limit ? str.slice(0, limit) + '…' : str
}
function injectMessagesIntoTemplate (template, body) {
if (!template || typeof template !== 'string') {
return body
}
const placeholders = ['${messages}', '{messages}', '{{messages}}']
let result = template
let replaced = false
for (const placeholder of placeholders) {
if (result.includes(placeholder)) {
result = result.split(placeholder).join(body)
replaced = true
}
}
if (!replaced) {
const trimmed = result.trim()
if (!trimmed) {
return body
}
if (/\n\s*$/.test(result)) {
return `${result}${body}`
}
return `${result}\n${body}`
}
return result
}
async function resolvePresetSendMessageOption (presetId, scope) {
if (!presetId) {
return null
}
try {
const chaite = Chaite.getInstance?.()
if (!chaite) {
logger.warn(`[Memory] ${scope} extraction preset ${presetId} configured but Chaite is not initialized`)
return null
}
const presetManager = chaite.getChatPresetManager?.()
if (!presetManager) {
logger.warn(`[Memory] ${scope} extraction preset ${presetId} configured but preset manager unavailable`)
return null
}
const preset = await presetManager.getInstance(presetId)
if (!preset) {
logger.warn(`[Memory] ${scope} extraction preset ${presetId} not found`)
return null
}
logger.debug(`[Memory] using ${scope} extraction preset ${presetId}`)
return {
preset,
sendMessageOption: JSON.parse(JSON.stringify(preset.sendMessageOption || {}))
}
} catch (err) {
logger.error(`[Memory] failed to load ${scope} extraction preset ${presetId}:`, err)
return null
}
}
function resolveGroupExtractionPrompts (presetSendMessageOption) {
const config = ChatGPTConfig.memory?.group || {}
const system = config.extractionSystemPrompt || presetSendMessageOption?.systemOverride || `You are a knowledge extraction assistant that specialises in summarising long-term facts from group chat transcripts.
Read the provided conversation and identify statements that should be stored as long-term knowledge for the group.
Return a JSON array. Each element must contain:
{
"fact": 事实内容必须完整包含事件的各个要素而不能是简单的短语比如谁参与了事件做了什么事情背景时间是什么同一件事情尽可能整合为同一条而非拆分以便利于检索,
"topic": 主题关键词字符串 "活动""成员信息",
"importance": 一个介于0和1之间的小数数值越大表示越重要,
"source_message_ids": 原始消息ID数组,
"source_messages": 对应原始消息的简要摘录或合并文本,
"involved_users": 出现或相关的用户ID数组
}
Only include meaningful, verifiable group-specific information that is useful for future conversations. Do not record incomplete information. Do not include general knowledge or unrelated facts. Do not wrap the JSON array in code fences.`
const userTemplate = config.extractionUserPrompt || `以下是群聊中的一些消息请根据系统说明提取值得长期记忆的事实以JSON数组形式返回不要输出额外说明。
\${messages}`
return { system, userTemplate }
}
function buildGroupUserPrompt (messages, template) {
const joined = messages.map(msg => {
const sender = msg.nickname || msg.user_id || '未知用户'
return `${sender}: ${msg.text}`
}).join('\n')
return injectMessagesIntoTemplate(template, joined)
}
function buildExistingMemorySection (existingMemories = []) {
if (!existingMemories || existingMemories.length === 0) {
return '当前没有任何已知的长期记忆。'
}
const lines = existingMemories.map((item, idx) => `${idx + 1}. ${item}`)
return `以下是关于用户的已知长期记忆,请在提取新记忆时参考,避免重复已有事实,并在信息变更时更新描述:\n${lines.join('\n')}`
}
function resolveUserExtractionPrompts (existingMemories = [], presetSendMessageOption) {
const config = ChatGPTConfig.memory?.user || {}
const systemTemplate = config.extractionSystemPrompt || presetSendMessageOption?.systemOverride || `You are an assistant that extracts long-term personal preferences or persona details about a user.
Given a conversation snippet between the user and the bot, identify durable information such as preferences, nicknames, roles, speaking style, habits, or other facts that remain valid over time.
Return a JSON array of **strings**, and nothing else, without any other characters including \`\`\` or \`\`\`json. Each string must be a short sentence (in the same language as the conversation) describing one piece of long-term memory. Do not include keys, JSON objects, or additional metadata. Ignore temporary topics or uncertain information.`
const userTemplate = config.extractionUserPrompt || `下面是用户与机器人的对话,请根据系统提示提取可长期记忆的个人信息。
\${messages}`
return {
system: `${systemTemplate}
${buildExistingMemorySection(existingMemories)}`,
userTemplate
}
}
function buildUserPrompt (messages, template) {
const body = messages.map(msg => {
const prefix = msg.role === 'assistant' ? '机器人' : (msg.nickname || msg.user_id || '用户')
return `${prefix}: ${msg.text}`
}).join('\n')
return injectMessagesIntoTemplate(template, body)
}
async function callModel ({ prompt, systemPrompt, model, maxToken = 4096, temperature = 0.2, sendMessageOption }) {
const options = sendMessageOption
? JSON.parse(JSON.stringify(sendMessageOption))
: {}
options.model = model || options.model
if (!options.model) {
throw new Error('No model available for memory extraction call')
}
const resolvedModel = options.model
const { client } = await getClientForModel(resolvedModel)
const response = await client.sendMessage({
role: 'user',
content: [
{
type: 'text',
text: prompt
}
]
}, SendMessageOption.create({
...options,
model: options.model,
temperature: options.temperature ?? temperature,
maxToken: options.maxToken ?? maxToken,
systemOverride: systemPrompt ?? options.systemOverride,
disableHistoryRead: true,
disableHistorySave: true,
stream: false
}))
return collectTextFromResponse(response)
}
function resolveGroupExtractionModel (presetSendMessageOption) {
const config = ChatGPTConfig.memory?.group
if (config?.extractionModel) {
return config.extractionModel
}
if (presetSendMessageOption?.model) {
return presetSendMessageOption.model
}
if (ChatGPTConfig.llm?.defaultModel) {
return ChatGPTConfig.llm.defaultModel
}
return ''
}
function resolveUserExtractionModel (presetSendMessageOption) {
const config = ChatGPTConfig.memory?.user
if (config?.extractionModel) {
return config.extractionModel
}
if (presetSendMessageOption?.model) {
return presetSendMessageOption.model
}
if (ChatGPTConfig.llm?.defaultModel) {
return ChatGPTConfig.llm.defaultModel
}
return ''
}
export async function extractGroupFacts (messages) {
if (!messages || messages.length === 0) {
return []
}
const groupConfig = ChatGPTConfig.memory?.group || {}
const presetInfo = await resolvePresetSendMessageOption(groupConfig.extractionPresetId, 'group')
const presetOptions = presetInfo?.sendMessageOption
const model = resolveGroupExtractionModel(presetOptions)
if (!model) {
logger.warn('No model configured for group memory extraction')
return []
}
try {
const prompts = resolveGroupExtractionPrompts(presetOptions)
logger.debug(`[Memory] start group fact extraction, messages=${messages.length}, model=${model}${presetInfo?.preset ? `, preset=${presetInfo.preset.id}` : ''}`)
const text = await callModel({
prompt: buildGroupUserPrompt(messages, prompts.userTemplate),
systemPrompt: prompts.system,
model,
sendMessageOption: presetOptions
})
const parsed = parseJSON(text)
if (Array.isArray(parsed)) {
logger.info(`[Memory] extracted ${parsed.length} group facts`)
parsed.slice(0, 10).forEach((item, idx) => {
logger.debug(`[Memory] group fact[${idx}] ${formatEntry(item)}`)
})
return parsed
}
logger.debug('[Memory] group fact extraction returned non-array content')
return []
} catch (err) {
logger.error('Failed to extract group facts:', err)
return []
}
}
export async function extractUserMemories (messages, existingMemories = []) {
if (!messages || messages.length === 0) {
return []
}
const userConfig = ChatGPTConfig.memory?.user || {}
const presetInfo = await resolvePresetSendMessageOption(userConfig.extractionPresetId, 'user')
const presetOptions = presetInfo?.sendMessageOption
const model = resolveUserExtractionModel(presetOptions)
if (!model) {
logger.warn('No model configured for user memory extraction')
return []
}
try {
const prompts = resolveUserExtractionPrompts(existingMemories, presetOptions)
logger.debug(`[Memory] start user memory extraction, snippets=${messages.length}, existing=${existingMemories.length}, model=${model}${presetInfo?.preset ? `, preset=${presetInfo.preset.id}` : ''}`)
const text = await callModel({
prompt: buildUserPrompt(messages, prompts.userTemplate),
systemPrompt: prompts.system,
model,
sendMessageOption: presetOptions
})
const parsed = parseJSON(text)
if (Array.isArray(parsed)) {
const sentences = parsed.map(item => {
if (typeof item === 'string') {
return item.trim()
}
if (item && typeof item === 'object') {
const possible = item.sentence || item.text || item.value || item.fact
if (possible) {
return String(possible).trim()
}
}
return ''
}).filter(Boolean)
logger.info(`[Memory] extracted ${sentences.length} user memories`)
sentences.slice(0, 10).forEach((item, idx) => {
logger.debug(`[Memory] user memory[${idx}] ${formatEntry(item)}`)
})
return sentences
}
logger.debug('[Memory] user memory extraction returned non-array content')
return []
} catch (err) {
logger.error('Failed to extract user memories:', err)
return []
}
}

View file

@ -0,0 +1,61 @@
import { getMemoryDatabase } from './database.js'
function normaliseGroupId (groupId) {
if (groupId === null || groupId === undefined) {
return null
}
const str = String(groupId).trim()
return str || null
}
export class GroupHistoryCursorStore {
constructor (db = getMemoryDatabase()) {
this.resetDatabase(db)
}
resetDatabase (db = getMemoryDatabase()) {
this.db = db
this.selectStmt = this.db.prepare(`
SELECT last_message_id, last_timestamp
FROM group_history_cursor
WHERE group_id = ?
`)
this.upsertStmt = this.db.prepare(`
INSERT INTO group_history_cursor (group_id, last_message_id, last_timestamp)
VALUES (@group_id, @last_message_id, @last_timestamp)
ON CONFLICT(group_id) DO UPDATE SET
last_message_id = excluded.last_message_id,
last_timestamp = excluded.last_timestamp
`)
}
ensureDb () {
if (!this.db || this.db.open === false) {
logger?.debug?.('[Memory] refreshing group history cursor database connection')
this.resetDatabase()
}
return this.db
}
getCursor (groupId) {
const gid = normaliseGroupId(groupId)
if (!gid) return null
this.ensureDb()
return this.selectStmt.get(gid) || null
}
updateCursor (groupId, { lastMessageId = null, lastTimestamp = null } = {}) {
const gid = normaliseGroupId(groupId)
if (!gid) return false
this.ensureDb()
const payload = {
group_id: gid,
last_message_id: lastMessageId ? String(lastMessageId) : null,
last_timestamp: (typeof lastTimestamp === 'number' && Number.isFinite(lastTimestamp)) ? Math.floor(lastTimestamp) : null
}
this.upsertStmt.run(payload)
return true
}
}
export const groupHistoryCursorStore = new GroupHistoryCursorStore()

View file

@ -0,0 +1,515 @@
import { getMemoryDatabase, getVectorDimension, getGroupMemoryFtsConfig, resetVectorTableDimension, sanitiseFtsQueryInput } from './database.js'
import ChatGPTConfig from '../../config/config.js'
import { embedTexts } from '../chaite/vectorizer.js'
function toJSONString (value) {
if (!value) {
return '[]'
}
if (Array.isArray(value)) {
return JSON.stringify(value)
}
return typeof value === 'string' ? value : JSON.stringify(value)
}
function toVectorBuffer (vector) {
if (!vector) {
return null
}
if (vector instanceof Float32Array) {
return Buffer.from(vector.buffer)
}
if (ArrayBuffer.isView(vector)) {
return Buffer.from(new Float32Array(vector).buffer)
}
return Buffer.from(new Float32Array(vector).buffer)
}
function normaliseEmbeddingVector (vector) {
if (!vector) {
return null
}
if (Array.isArray(vector)) {
return vector
}
if (ArrayBuffer.isView(vector)) {
return Array.from(vector)
}
if (typeof vector === 'object') {
if (Array.isArray(vector.embedding)) {
return vector.embedding
}
if (ArrayBuffer.isView(vector.embedding)) {
return Array.from(vector.embedding)
}
if (Array.isArray(vector.vector)) {
return vector.vector
}
if (ArrayBuffer.isView(vector.vector)) {
return Array.from(vector.vector)
}
}
return null
}
function normaliseGroupId (groupId) {
return groupId === null || groupId === undefined ? null : String(groupId)
}
export class GroupMemoryStore {
constructor (db = getMemoryDatabase()) {
this.resetDatabase(db)
}
resetDatabase (db = getMemoryDatabase()) {
this.db = db
this.insertFactStmt = this.db.prepare(`
INSERT INTO group_facts (group_id, fact, topic, importance, source_message_ids, source_messages, involved_users)
VALUES (@group_id, @fact, @topic, @importance, @source_message_ids, @source_messages, @involved_users)
ON CONFLICT(group_id, fact) DO UPDATE SET
topic = excluded.topic,
importance = excluded.importance,
source_message_ids = excluded.source_message_ids,
source_messages = excluded.source_messages,
involved_users = excluded.involved_users,
created_at = CASE
WHEN excluded.importance > group_facts.importance THEN datetime('now')
ELSE group_facts.created_at
END
`)
this.prepareVectorStatements()
this.loadFactByIdStmt = this.db.prepare('SELECT * FROM group_facts WHERE id = ?')
}
prepareVectorStatements () {
try {
this.deleteVecStmt = this.db.prepare('DELETE FROM vec_group_facts WHERE rowid = ?')
this.insertVecStmt = this.db.prepare('INSERT INTO vec_group_facts(rowid, embedding) VALUES (?, ?)')
} catch (err) {
this.deleteVecStmt = null
this.insertVecStmt = null
logger?.debug?.('[Memory] vector table not ready, postpone statement preparation')
}
}
ensureDb () {
if (!this.db || this.db.open === false) {
logger?.debug?.('[Memory] refreshing group memory database connection')
this.resetDatabase()
}
return this.db
}
get embeddingModel () {
return ChatGPTConfig.llm?.embeddingModel || ''
}
get retrievalMode () {
const mode = ChatGPTConfig.memory?.group?.retrievalMode || 'hybrid'
const lowered = String(mode).toLowerCase()
if (['vector', 'keyword', 'hybrid'].includes(lowered)) {
return lowered
}
return 'hybrid'
}
get hybridPrefer () {
const prefer = ChatGPTConfig.memory?.group?.hybridPrefer || 'vector-first'
return prefer === 'keyword-first' ? 'keyword-first' : 'vector-first'
}
isVectorEnabled () {
return Boolean(this.embeddingModel)
}
get vectorDistanceThreshold () {
const value = Number(ChatGPTConfig.memory?.group?.vectorMaxDistance)
if (Number.isFinite(value) && value > 0) {
return value
}
return null
}
get bm25Threshold () {
const value = Number(ChatGPTConfig.memory?.group?.textMaxBm25Score)
if (Number.isFinite(value) && value > 0) {
return value
}
return null
}
async saveFacts (groupId, facts) {
if (!facts || facts.length === 0) {
return []
}
this.ensureDb()
const normGroupId = normaliseGroupId(groupId)
const filteredFacts = facts
.map(f => {
const rawFact = typeof f.fact === 'string' ? f.fact : (Array.isArray(f.fact) ? f.fact.join(' ') : String(f.fact || ''))
const rawTopic = typeof f.topic === 'string' ? f.topic : (f.topic === undefined || f.topic === null ? '' : String(f.topic))
const rawSourceMessages = f.source_messages ?? f.sourceMessages ?? ''
const sourceMessages = Array.isArray(rawSourceMessages)
? rawSourceMessages.map(item => (item === null || item === undefined) ? '' : String(item)).filter(Boolean).join('\n')
: (typeof rawSourceMessages === 'string' ? rawSourceMessages : String(rawSourceMessages || ''))
return {
fact: rawFact.trim(),
topic: rawTopic.trim(),
importance: typeof f.importance === 'number' ? f.importance : Number(f.importance) || 0.5,
source_message_ids: toJSONString(f.source_message_ids || f.sourceMessages),
source_messages: sourceMessages,
involved_users: toJSONString(f.involved_users || f.involvedUsers || [])
}
})
.filter(item => item.fact)
if (filteredFacts.length === 0) {
return []
}
let vectors = []
let tableDimension = getVectorDimension() || 0
const configuredDimension = Number(ChatGPTConfig.llm?.dimensions || 0)
if (this.isVectorEnabled()) {
try {
const preferredDimension = configuredDimension > 0
? configuredDimension
: (tableDimension > 0 ? tableDimension : undefined)
vectors = await embedTexts(filteredFacts.map(f => f.fact), this.embeddingModel, preferredDimension)
vectors = vectors.map(normaliseEmbeddingVector)
const mismatchVector = vectors.find(vec => {
if (!vec) return false
if (Array.isArray(vec)) return vec.length > 0
if (ArrayBuffer.isView(vec) && typeof vec.length === 'number') {
return vec.length > 0
}
return false
})
const actualDimension = mismatchVector ? mismatchVector.length : 0
if (actualDimension && actualDimension !== tableDimension) {
const expectedDimension = tableDimension || preferredDimension || configuredDimension || 'unknown'
logger.warn(`[Memory] embedding dimension mismatch, expected=${expectedDimension}, actual=${actualDimension}. Recreating vector table.`)
try {
resetVectorTableDimension(actualDimension)
this.prepareVectorStatements()
tableDimension = actualDimension
} catch (resetErr) {
logger.error('Failed to reset vector table dimension:', resetErr)
vectors = []
}
} else if (actualDimension && tableDimension <= 0) {
try {
resetVectorTableDimension(actualDimension)
this.prepareVectorStatements()
tableDimension = actualDimension
} catch (resetErr) {
logger.error('Failed to initialise vector table dimension:', resetErr)
vectors = []
}
}
} catch (err) {
logger.error('Failed to embed group facts:', err)
vectors = []
}
}
const transaction = this.db.transaction((items, vectorList) => {
const saved = []
for (let i = 0; i < items.length; i++) {
const payload = {
group_id: normGroupId,
...items[i]
}
const info = this.insertFactStmt.run(payload)
let factId = Number(info.lastInsertRowid)
if (!factId) {
const existing = this.db.prepare('SELECT id FROM group_facts WHERE group_id = ? AND fact = ?').get(normGroupId, payload.fact)
factId = existing?.id
}
factId = Number.parseInt(String(factId ?? ''), 10)
if (!Number.isSafeInteger(factId)) {
logger.warn('[Memory] skip fact vector upsert due to invalid fact id', factId)
continue
}
if (!factId) {
continue
}
if (Array.isArray(vectorList) && vectorList[i]) {
if (!this.deleteVecStmt || !this.insertVecStmt) {
this.prepareVectorStatements()
}
if (!this.deleteVecStmt || !this.insertVecStmt) {
logger.warn('[Memory] vector table unavailable, skip vector upsert')
continue
}
try {
const vector = normaliseEmbeddingVector(vectorList[i])
if (!vector) {
continue
}
let embeddingArray
if (ArrayBuffer.isView(vector)) {
if (vector instanceof Float32Array) {
embeddingArray = vector
} else {
embeddingArray = new Float32Array(vector.length)
for (let idx = 0; idx < vector.length; idx++) {
embeddingArray[idx] = Number(vector[idx])
}
}
} else {
embeddingArray = Float32Array.from(vector)
}
const rowId = BigInt(factId)
logger.debug(`[Memory] upserting vector for fact ${factId}, rowIdType=${typeof rowId}`)
this.deleteVecStmt.run(rowId)
this.insertVecStmt.run(rowId, embeddingArray)
} catch (error) {
logger.error(`Failed to upsert vector for fact ${factId}:`, error)
}
}
saved.push(this.loadFactByIdStmt.get(factId))
}
return saved
})
return transaction(filteredFacts, vectors)
}
listFacts (groupId, limit = 50, offset = 0) {
return this.db.prepare(`
SELECT * FROM group_facts
WHERE group_id = ?
ORDER BY importance DESC, created_at DESC
LIMIT ? OFFSET ?
`).all(normaliseGroupId(groupId), limit, offset)
}
deleteFact (groupId, factId) {
this.ensureDb()
const normGroupId = normaliseGroupId(groupId)
const fact = this.db.prepare('SELECT id FROM group_facts WHERE id = ? AND group_id = ?').get(factId, normGroupId)
if (!fact) {
return false
}
this.db.prepare('DELETE FROM group_facts WHERE id = ?').run(factId)
try {
this.deleteVecStmt.run(BigInt(factId))
} catch (err) {
logger?.warn?.(`[Memory] failed to delete vector for fact ${factId}:`, err)
}
return true
}
async vectorSearch (groupId, queryText, limit) {
this.ensureDb()
if (!this.isVectorEnabled()) {
return []
}
try {
let tableDimension = getVectorDimension() || 0
if (!tableDimension || tableDimension <= 0) {
logger.debug('[Memory] vector table dimension unavailable, attempting to infer from embedding')
}
const requestedDimension = tableDimension > 0 ? tableDimension : undefined
const [embedding] = await embedTexts([queryText], this.embeddingModel, requestedDimension)
if (!embedding) {
return []
}
const embeddingVector = ArrayBuffer.isView(embedding) ? embedding : Float32Array.from(embedding)
const actualDimension = embeddingVector.length
if (!actualDimension) {
logger.debug('[Memory] vector search skipped: empty embedding returned')
return []
}
if (tableDimension > 0 && actualDimension !== tableDimension) {
logger.warn(`[Memory] vector dimension mismatch detected during search, table=${tableDimension}, embedding=${actualDimension}. Rebuilding vector table.`)
try {
resetVectorTableDimension(actualDimension)
this.prepareVectorStatements()
tableDimension = actualDimension
} catch (resetErr) {
logger.error('Failed to reset vector table dimension during search:', resetErr)
return []
}
logger.info('[Memory] vector table rebuilt; old vectors must be regenerated before vector search can return results')
return []
} else if (tableDimension <= 0 && actualDimension > 0) {
try {
resetVectorTableDimension(actualDimension)
this.prepareVectorStatements()
tableDimension = actualDimension
} catch (resetErr) {
logger.error('Failed to initialise vector table dimension during search:', resetErr)
return []
}
}
const rows = this.db.prepare(`
SELECT gf.*, vec_group_facts.distance AS distance
FROM vec_group_facts
JOIN group_facts gf ON gf.id = vec_group_facts.rowid
WHERE gf.group_id = ?
AND vec_group_facts.embedding MATCH ?
AND vec_group_facts.k = ${limit}
ORDER BY distance ASC
`).all(groupId, embeddingVector)
const threshold = this.vectorDistanceThreshold
if (!threshold) {
return rows
}
return rows.filter(row => typeof row?.distance === 'number' && row.distance <= threshold)
} catch (err) {
logger.warn('Vector search failed for group memory:', err)
return []
}
}
textSearch (groupId, queryText, limit) {
this.ensureDb()
if (!queryText || !queryText.trim()) {
return []
}
const originalQuery = queryText.trim()
const ftsConfig = getGroupMemoryFtsConfig()
const matchQueryParam = sanitiseFtsQueryInput(originalQuery, ftsConfig)
const results = []
const seen = new Set()
if (matchQueryParam) {
const matchExpression = ftsConfig.matchQuery ? `${ftsConfig.matchQuery}(?)` : '?'
try {
const rows = this.db.prepare(`
SELECT gf.*, bm25(group_facts_fts) AS bm25_score
FROM group_facts_fts
JOIN group_facts gf ON gf.id = group_facts_fts.rowid
WHERE gf.group_id = ?
AND group_facts_fts MATCH ${matchExpression}
ORDER BY bm25_score ASC
LIMIT ?
`).all(groupId, matchQueryParam, limit)
for (const row of rows) {
const bm25Threshold = this.bm25Threshold
if (bm25Threshold) {
const score = Number(row?.bm25_score)
if (!Number.isFinite(score) || score > bm25Threshold) {
continue
}
row.bm25_score = score
}
if (row && !seen.has(row.id)) {
results.push(row)
seen.add(row.id)
}
}
} catch (err) {
logger.warn('Text search failed for group memory:', err)
}
} else {
logger.debug('[Memory] group memory text search skipped MATCH due to empty query after sanitisation')
}
if (results.length < limit) {
try {
const likeRows = this.db.prepare(`
SELECT *
FROM group_facts
WHERE group_id = ?
AND instr(fact, ?) > 0
ORDER BY importance DESC, created_at DESC
LIMIT ?
`).all(groupId, originalQuery, Math.max(limit * 2, limit))
for (const row of likeRows) {
if (row && !seen.has(row.id)) {
results.push(row)
seen.add(row.id)
if (results.length >= limit) {
break
}
}
}
} catch (err) {
logger.warn('LIKE fallback failed for group memory:', err)
}
}
return results.slice(0, limit)
}
importanceFallback (groupId, limit, minImportance, excludeIds = []) {
this.ensureDb()
const ids = excludeIds.filter(Boolean)
const notInClause = ids.length ? `AND id NOT IN (${ids.map(() => '?').join(',')})` : ''
const stmt = this.db.prepare(`
SELECT * FROM group_facts
WHERE group_id = ?
AND importance >= ?
${notInClause}
ORDER BY importance DESC, created_at DESC
LIMIT ?
`)
const params = [groupId, minImportance]
if (ids.length) {
params.push(...ids)
}
params.push(limit)
return stmt.all(...params)
}
/**
* 获取相关群记忆支持向量/文本/混合检索
* @param {string} groupId
* @param {string} queryText
* @param {{ limit?: number, minImportance?: number }} options
* @returns {Promise<Array<{fact: string, topic: string, importance: number, created_at: string}>>}
*/
async queryRelevantFacts (groupId, queryText, options = {}) {
const { limit = 5, minImportance = 0 } = options
const normGroupId = normaliseGroupId(groupId)
if (!queryText) {
return this.listFacts(normGroupId, limit)
}
const mode = this.retrievalMode
const combined = []
const seen = new Set()
const append = rows => {
for (const row of rows) {
if (!row || seen.has(row.id)) {
continue
}
combined.push(row)
seen.add(row.id)
if (combined.length >= limit) {
break
}
}
}
const preferVector = this.hybridPrefer !== 'keyword-first'
if (mode === 'vector' || mode === 'hybrid') {
const vectorRows = await this.vectorSearch(normGroupId, queryText, limit)
if (mode === 'vector') {
append(vectorRows)
} else if (preferVector) {
append(vectorRows)
if (combined.length < limit) {
append(this.textSearch(normGroupId, queryText, limit))
}
} else {
append(this.textSearch(normGroupId, queryText, limit))
if (combined.length < limit) {
append(vectorRows)
}
}
} else if (mode === 'keyword') {
append(this.textSearch(normGroupId, queryText, limit))
}
if (combined.length < limit) {
const fallback = this.importanceFallback(normGroupId, limit - combined.length, minImportance, Array.from(seen))
append(fallback)
}
return combined.slice(0, limit)
}
}

128
models/memory/prompt.js Normal file
View file

@ -0,0 +1,128 @@
import ChatGPTConfig from '../../config/config.js'
import { memoryService } from './service.js'
function renderTemplate (template, context = {}) {
if (!template) {
return ''
}
return template.replace(/\$\{(\w+)\}/g, (_, key) => {
const value = context[key]
return value === undefined || value === null ? '' : String(value)
})
}
function formatUserMemories (memories, config) {
if (!memories.length) {
return ''
}
const headerTemplate = config.promptHeader ?? '# 用户画像'
const itemTemplate = config.promptItemTemplate ?? '- ${value}'
const footerTemplate = config.promptFooter ?? ''
const segments = []
const header = renderTemplate(headerTemplate, { count: memories.length })
if (header) {
segments.push(header)
}
memories.forEach((item, index) => {
const timestamp = item.updated_at || item.created_at || ''
const timeSuffix = timestamp ? `(记录时间:${timestamp}` : ''
const context = {
index,
order: index + 1,
value: item.value || '',
importance: item.importance ?? '',
sourceMessageId: item.source_message_id || '',
sourceId: item.source_message_id || '',
groupId: item.group_id || '',
createdAt: item.created_at || '',
updatedAt: item.updated_at || '',
timestamp,
time: timestamp,
timeSuffix
}
const line = renderTemplate(itemTemplate, context)
if (line) {
segments.push(line)
}
})
const footer = renderTemplate(footerTemplate, { count: memories.length })
if (footer) {
segments.push(footer)
}
return segments.join('\n')
}
function formatGroupFacts (facts, config) {
if (!facts.length) {
return ''
}
const headerTemplate = config.promptHeader ?? '# 群聊长期记忆'
const itemTemplate = config.promptItemTemplate ?? '- ${fact}${topicSuffix}'
const footerTemplate = config.promptFooter ?? ''
const segments = []
const header = renderTemplate(headerTemplate, { count: facts.length })
if (header) {
segments.push(header)
}
facts.forEach((item, index) => {
const topicSuffix = item.topic ? `${item.topic}` : ''
const timestamp = item.updated_at || item.created_at || ''
const timeSuffix = timestamp ? `(记录时间:${timestamp}` : ''
const context = {
index,
order: index + 1,
fact: item.fact || '',
topic: item.topic || '',
topicSuffix,
importance: item.importance ?? '',
createdAt: item.created_at || '',
updatedAt: item.updated_at || '',
timestamp,
time: timestamp,
timeSuffix,
distance: item.distance ?? '',
bm25: item.bm25_score ?? '',
sourceMessages: item.source_messages || '',
sourceMessageIds: item.source_message_ids || ''
}
const line = renderTemplate(itemTemplate, context)
if (line) {
segments.push(line)
}
})
const footer = renderTemplate(footerTemplate, { count: facts.length })
if (footer) {
segments.push(footer)
}
return segments.join('\n')
}
export async function buildMemoryPrompt ({ userId, groupId, queryText }) {
const segments = []
const userConfig = ChatGPTConfig.memory?.user || {}
const groupConfig = ChatGPTConfig.memory?.group || {}
if (memoryService.isUserMemoryEnabled(userId)) {
const totalLimit = userConfig.maxItemsPerInjection || 5
const searchLimit = Math.min(userConfig.maxRelevantItemsPerQuery || totalLimit, totalLimit)
const userMemories = memoryService.queryUserMemories(userId, groupId, queryText, {
totalLimit,
searchLimit,
minImportance: userConfig.minImportanceForInjection ?? 0
})
const userSegment = formatUserMemories(userMemories, userConfig)
if (userSegment) {
segments.push(userSegment)
}
}
if (groupId && memoryService.isGroupMemoryEnabled(groupId)) {
const facts = await memoryService.queryGroupFacts(groupId, queryText, {
limit: groupConfig.maxFactsPerInjection || 5,
minImportance: groupConfig.minImportanceForInjection || 0
})
const groupSegment = formatGroupFacts(facts, groupConfig)
if (groupSegment) {
segments.push(groupSegment)
}
}
return segments.join('\n\n').trim()
}

726
models/memory/router.js Normal file
View file

@ -0,0 +1,726 @@
import express from 'express'
import fs from 'fs'
import os from 'os'
import path from 'path'
import https from 'https'
import { pipeline } from 'stream'
import { promisify } from 'util'
let AdmZip
try {
AdmZip = (await import('adm-zip')).default
} catch (e) {
logger.warn('Failed to load AdmZip, maybe you need to install it manually:', e)
}
import { execSync } from "child_process"
import {
Chaite,
ChaiteResponse,
FrontEndAuthHandler
} from 'chaite'
import ChatGPTConfig from '../../config/config.js'
import { memoryService } from './service.js'
import {
resetCachedDimension,
resetMemoryDatabaseInstance,
getSimpleExtensionState,
resolvePluginPath,
toPluginRelativePath,
resetVectorTableDimension
} from './database.js'
const streamPipeline = promisify(pipeline)
const SIMPLE_DOWNLOAD_BASE_URL = 'https://github.com/wangfenjin/simple/releases/latest/download'
const SIMPLE_ASSET_MAP = {
'linux-x64': 'libsimple-linux-ubuntu-latest.zip',
'linux-arm64': 'libsimple-linux-ubuntu-24.04-arm.zip',
'linux-arm': 'libsimple-linux-ubuntu-24.04-arm.zip',
'darwin-x64': 'libsimple-osx-x64.zip',
'darwin-arm64': 'libsimple-osx-x64.zip',
'win32-x64': 'libsimple-windows-x64.zip',
'win32-ia32': 'libsimple-windows-x86.zip',
'win32-arm64': 'libsimple-windows-arm64.zip'
}
const DEFAULT_SIMPLE_INSTALL_DIR = 'resources/simple'
export function authenticateMemoryRequest (req, res, next) {
const bearer = req.header('Authorization') || ''
const token = bearer.replace(/^Bearer\s+/i, '').trim()
if (!token) {
res.status(401).json({ message: 'Access denied, token missing' })
return
}
try {
const authKey = Chaite.getInstance()?.getGlobalConfig()?.getAuthKey()
if (authKey && FrontEndAuthHandler.validateJWT(authKey, token)) {
next()
return
}
res.status(401).json({ message: 'Invalid token' })
} catch (error) {
res.status(401).json({ message: 'Invalid token format' })
}
}
function parsePositiveInt (value, fallback) {
const num = Number(value)
return Number.isInteger(num) && num >= 0 ? num : fallback
}
function parseNumber (value, fallback) {
const num = Number(value)
return Number.isFinite(num) ? num : fallback
}
function toStringArray (value) {
if (!Array.isArray(value)) {
return []
}
return value
.map(item => {
if (item === undefined || item === null) {
return null
}
return String(item).trim()
})
.filter(item => item)
}
function parseOptionalStringParam (value) {
if (Array.isArray(value)) {
value = value[0]
}
if (value === undefined || value === null) {
return null
}
const trimmed = String(value).trim()
if (!trimmed || trimmed.toLowerCase() === 'null' || trimmed.toLowerCase() === 'undefined') {
return null
}
return trimmed
}
function detectAssetKey (platform, arch) {
const normalizedArch = arch === 'arm64' ? 'arm64' : (arch === 'arm' ? 'arm' : (arch === 'ia32' ? 'ia32' : 'x64'))
const key = `${platform}-${normalizedArch}`
if (SIMPLE_ASSET_MAP[key]) {
return key
}
if (platform === 'darwin' && SIMPLE_ASSET_MAP['darwin-x64']) {
return 'darwin-x64'
}
if (platform === 'linux' && SIMPLE_ASSET_MAP['linux-x64']) {
return 'linux-x64'
}
if (platform === 'win32' && SIMPLE_ASSET_MAP['win32-x64']) {
return 'win32-x64'
}
return null
}
function resolveSimpleAsset (requestedKey, requestedAsset) {
if (requestedAsset) {
return {
key: requestedKey || 'custom',
asset: requestedAsset
}
}
if (requestedKey && SIMPLE_ASSET_MAP[requestedKey]) {
return {
key: requestedKey,
asset: SIMPLE_ASSET_MAP[requestedKey]
}
}
const autoKey = detectAssetKey(process.platform, process.arch)
if (autoKey && SIMPLE_ASSET_MAP[autoKey]) {
return { key: autoKey, asset: SIMPLE_ASSET_MAP[autoKey] }
}
return { key: null, asset: null }
}
function ensureDirectoryExists (dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true })
}
}
async function downloadToFile (url, destination, redirectCount = 0) {
if (redirectCount > 5) {
throw new Error('Too many redirects while downloading extension')
}
await new Promise((resolve, reject) => {
const request = https.get(url, {
headers: {
'User-Agent': 'chatgpt-plugin-memory-extension-downloader'
}
}, async res => {
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
res.resume()
try {
await downloadToFile(res.headers.location, destination, redirectCount + 1)
resolve()
} catch (err) {
reject(err)
}
return
}
if (res.statusCode !== 200) {
reject(new Error(`Failed to download extension: HTTP ${res.statusCode}`))
res.resume()
return
}
const fileStream = fs.createWriteStream(destination)
streamPipeline(res, fileStream).then(resolve).catch(reject)
})
request.on('error', error => reject(error))
})
}
function removeDirectoryIfExists (dirPath) {
if (fs.existsSync(dirPath)) {
fs.rmSync(dirPath, { recursive: true, force: true })
}
}
function findLibraryFile (rootDir) {
const entries = fs.readdirSync(rootDir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(rootDir, entry.name)
if (entry.isDirectory()) {
const found = findLibraryFile(fullPath)
if (found) {
return found
}
} else if (/simple\.(so|dylib|dll)$/i.test(entry.name) || /^libsimple/i.test(entry.name)) {
return fullPath
}
}
return null
}
function findDictDirectory (rootDir) {
const directDictPath = path.join(rootDir, 'dict')
if (fs.existsSync(directDictPath) && fs.statSync(directDictPath).isDirectory()) {
return directDictPath
}
const entries = fs.readdirSync(rootDir, { withFileTypes: true })
for (const entry of entries) {
if (entry.isDirectory()) {
const match = findDictDirectory(path.join(rootDir, entry.name))
if (match) {
return match
}
}
}
return null
}
async function downloadSimpleExtensionArchive ({ assetKey, assetName, targetDir }) {
if (!assetName) {
throw new Error('Simple extension asset name is required.')
}
const downloadUrl = `${SIMPLE_DOWNLOAD_BASE_URL}/${assetName}`
const tempFile = path.join(os.tmpdir(), `libsimple-${Date.now()}-${Math.random().toString(16).slice(2)}.zip`)
ensureDirectoryExists(path.dirname(tempFile))
await downloadToFile(downloadUrl, tempFile)
removeDirectoryIfExists(targetDir)
ensureDirectoryExists(targetDir)
if (AdmZip) {
try {
const zip = new AdmZip(tempFile)
zip.extractAllTo(targetDir, true)
} finally {
if (fs.existsSync(tempFile)) {
fs.unlinkSync(tempFile)
}
}
} else {
// 尝试使用 unzip 命令解压
try {
execSync(`unzip "${tempFile}" -d "${targetDir}"`, { stdio: 'inherit' })
} catch (error) {
throw new Error(`Failed to extract zip file: ${error.message}. Please install adm-zip manually: pnpm i`)
} finally {
if (fs.existsSync(tempFile)) {
fs.unlinkSync(tempFile)
}
}
}
const libraryFile = findLibraryFile(targetDir)
if (!libraryFile) {
throw new Error('Downloaded extension package does not contain libsimple library.')
}
const dictDir = findDictDirectory(targetDir)
if (!ChatGPTConfig.memory.extensions) {
ChatGPTConfig.memory.extensions = {}
}
if (!ChatGPTConfig.memory.extensions.simple) {
ChatGPTConfig.memory.extensions.simple = {
enable: false,
libraryPath: '',
dictPath: '',
useJieba: false
}
}
const relativeLibraryPath = toPluginRelativePath(libraryFile)
const relativeDictPath = dictDir ? toPluginRelativePath(dictDir) : ''
ChatGPTConfig.memory.extensions.simple.libraryPath = relativeLibraryPath
ChatGPTConfig.memory.extensions.simple.dictPath = relativeDictPath
return {
assetKey,
assetName,
installDir: toPluginRelativePath(targetDir),
libraryPath: relativeLibraryPath,
dictPath: ChatGPTConfig.memory.extensions.simple.dictPath
}
}
function updateMemoryConfig (payload = {}) {
const current = ChatGPTConfig.memory || {}
const previousDatabase = current.database
const previousDimension = current.vectorDimensions
const nextConfig = {
...current,
group: {
...(current.group || {})
},
user: {
...(current.user || {})
},
extensions: {
...(current.extensions || {}),
simple: {
...(current.extensions?.simple || {})
}
}
}
const previousSimpleConfig = JSON.stringify(current.extensions?.simple || {})
if (Object.prototype.hasOwnProperty.call(payload, 'database') && typeof payload.database === 'string') {
nextConfig.database = payload.database.trim()
}
if (Object.prototype.hasOwnProperty.call(payload, 'vectorDimensions')) {
const dimension = parsePositiveInt(payload.vectorDimensions, current.vectorDimensions || 1536)
if (dimension > 0) {
nextConfig.vectorDimensions = dimension
}
}
if (payload.group && typeof payload.group === 'object') {
const incomingGroup = payload.group
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'enable')) {
nextConfig.group.enable = Boolean(incomingGroup.enable)
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'enabledGroups')) {
nextConfig.group.enabledGroups = toStringArray(incomingGroup.enabledGroups)
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'extractionModel') && typeof incomingGroup.extractionModel === 'string') {
nextConfig.group.extractionModel = incomingGroup.extractionModel.trim()
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'extractionPresetId') && typeof incomingGroup.extractionPresetId === 'string') {
nextConfig.group.extractionPresetId = incomingGroup.extractionPresetId.trim()
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'minMessageCount')) {
nextConfig.group.minMessageCount = parsePositiveInt(incomingGroup.minMessageCount, nextConfig.group.minMessageCount || 0)
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'maxMessageWindow')) {
nextConfig.group.maxMessageWindow = parsePositiveInt(incomingGroup.maxMessageWindow, nextConfig.group.maxMessageWindow || 0)
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'retrievalMode')) {
const mode = String(incomingGroup.retrievalMode || '').toLowerCase()
if (['vector', 'keyword', 'hybrid'].includes(mode)) {
nextConfig.group.retrievalMode = mode
}
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'hybridPrefer')) {
const prefer = String(incomingGroup.hybridPrefer || '').toLowerCase()
if (prefer === 'keyword-first') {
nextConfig.group.hybridPrefer = 'keyword-first'
} else if (prefer === 'vector-first') {
nextConfig.group.hybridPrefer = 'vector-first'
}
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'historyPollInterval')) {
nextConfig.group.historyPollInterval = parsePositiveInt(incomingGroup.historyPollInterval,
nextConfig.group.historyPollInterval || 0)
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'historyBatchSize')) {
nextConfig.group.historyBatchSize = parsePositiveInt(incomingGroup.historyBatchSize,
nextConfig.group.historyBatchSize || 0)
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'promptHeader') && typeof incomingGroup.promptHeader === 'string') {
nextConfig.group.promptHeader = incomingGroup.promptHeader
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'promptItemTemplate') && typeof incomingGroup.promptItemTemplate === 'string') {
nextConfig.group.promptItemTemplate = incomingGroup.promptItemTemplate
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'promptFooter') && typeof incomingGroup.promptFooter === 'string') {
nextConfig.group.promptFooter = incomingGroup.promptFooter
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'vectorMaxDistance')) {
const distance = parseNumber(incomingGroup.vectorMaxDistance,
nextConfig.group.vectorMaxDistance ?? 0)
nextConfig.group.vectorMaxDistance = distance
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'textMaxBm25Score')) {
const bm25 = parseNumber(incomingGroup.textMaxBm25Score,
nextConfig.group.textMaxBm25Score ?? 0)
nextConfig.group.textMaxBm25Score = bm25
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'maxFactsPerInjection')) {
nextConfig.group.maxFactsPerInjection = parsePositiveInt(incomingGroup.maxFactsPerInjection,
nextConfig.group.maxFactsPerInjection || 0)
}
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'minImportanceForInjection')) {
const importance = parseNumber(incomingGroup.minImportanceForInjection,
nextConfig.group.minImportanceForInjection ?? 0)
nextConfig.group.minImportanceForInjection = importance
}
}
if (payload.user && typeof payload.user === 'object') {
const incomingUser = payload.user
if (Object.prototype.hasOwnProperty.call(incomingUser, 'enable')) {
nextConfig.user.enable = Boolean(incomingUser.enable)
}
if (Object.prototype.hasOwnProperty.call(incomingUser, 'whitelist')) {
nextConfig.user.whitelist = toStringArray(incomingUser.whitelist)
}
if (Object.prototype.hasOwnProperty.call(incomingUser, 'blacklist')) {
nextConfig.user.blacklist = toStringArray(incomingUser.blacklist)
}
if (Object.prototype.hasOwnProperty.call(incomingUser, 'extractionModel') && typeof incomingUser.extractionModel === 'string') {
nextConfig.user.extractionModel = incomingUser.extractionModel.trim()
}
if (Object.prototype.hasOwnProperty.call(incomingUser, 'extractionPresetId') && typeof incomingUser.extractionPresetId === 'string') {
nextConfig.user.extractionPresetId = incomingUser.extractionPresetId.trim()
}
if (Object.prototype.hasOwnProperty.call(incomingUser, 'maxItemsPerInjection')) {
nextConfig.user.maxItemsPerInjection = parsePositiveInt(incomingUser.maxItemsPerInjection,
nextConfig.user.maxItemsPerInjection || 0)
}
if (Object.prototype.hasOwnProperty.call(incomingUser, 'maxRelevantItemsPerQuery')) {
nextConfig.user.maxRelevantItemsPerQuery = parsePositiveInt(incomingUser.maxRelevantItemsPerQuery,
nextConfig.user.maxRelevantItemsPerQuery || 0)
}
if (Object.prototype.hasOwnProperty.call(incomingUser, 'minImportanceForInjection')) {
const importance = parseNumber(incomingUser.minImportanceForInjection,
nextConfig.user.minImportanceForInjection ?? 0)
nextConfig.user.minImportanceForInjection = importance
}
if (Object.prototype.hasOwnProperty.call(incomingUser, 'promptHeader') && typeof incomingUser.promptHeader === 'string') {
nextConfig.user.promptHeader = incomingUser.promptHeader
}
if (Object.prototype.hasOwnProperty.call(incomingUser, 'promptItemTemplate') && typeof incomingUser.promptItemTemplate === 'string') {
nextConfig.user.promptItemTemplate = incomingUser.promptItemTemplate
}
if (Object.prototype.hasOwnProperty.call(incomingUser, 'promptFooter') && typeof incomingUser.promptFooter === 'string') {
nextConfig.user.promptFooter = incomingUser.promptFooter
}
}
if (payload.extensions && typeof payload.extensions === 'object' && !Array.isArray(payload.extensions)) {
const incomingExtensions = payload.extensions
if (incomingExtensions.simple && typeof incomingExtensions.simple === 'object' && !Array.isArray(incomingExtensions.simple)) {
const incomingSimple = incomingExtensions.simple
if (Object.prototype.hasOwnProperty.call(incomingSimple, 'enable')) {
nextConfig.extensions.simple.enable = Boolean(incomingSimple.enable)
}
if (Object.prototype.hasOwnProperty.call(incomingSimple, 'libraryPath') && typeof incomingSimple.libraryPath === 'string') {
nextConfig.extensions.simple.libraryPath = incomingSimple.libraryPath.trim()
}
if (Object.prototype.hasOwnProperty.call(incomingSimple, 'dictPath') && typeof incomingSimple.dictPath === 'string') {
nextConfig.extensions.simple.dictPath = incomingSimple.dictPath.trim()
}
if (Object.prototype.hasOwnProperty.call(incomingSimple, 'useJieba')) {
nextConfig.extensions.simple.useJieba = Boolean(incomingSimple.useJieba)
}
} else if (Object.prototype.hasOwnProperty.call(incomingExtensions, 'simple')) {
logger.warn('[Memory] Unexpected value for extensions.simple, ignoring:', incomingExtensions.simple)
}
}
ChatGPTConfig.memory.database = nextConfig.database
ChatGPTConfig.memory.vectorDimensions = nextConfig.vectorDimensions
if (!ChatGPTConfig.memory.group) ChatGPTConfig.memory.group = {}
if (!ChatGPTConfig.memory.user) ChatGPTConfig.memory.user = {}
if (!ChatGPTConfig.memory.extensions) ChatGPTConfig.memory.extensions = {}
if (!ChatGPTConfig.memory.extensions.simple) {
ChatGPTConfig.memory.extensions.simple = {
enable: false,
libraryPath: '',
dictPath: '',
useJieba: false
}
}
Object.assign(ChatGPTConfig.memory.group, nextConfig.group)
Object.assign(ChatGPTConfig.memory.user, nextConfig.user)
Object.assign(ChatGPTConfig.memory.extensions.simple, nextConfig.extensions.simple)
if (nextConfig.vectorDimensions !== previousDimension) {
resetCachedDimension()
const targetDimension = Number(nextConfig.vectorDimensions)
if (Number.isFinite(targetDimension) && targetDimension > 0) {
try {
resetVectorTableDimension(targetDimension)
} catch (err) {
logger?.error?.('[Memory] failed to apply vector dimension change:', err)
}
}
}
const currentSimpleConfig = JSON.stringify(ChatGPTConfig.memory.extensions?.simple || {})
if (nextConfig.database !== previousDatabase) {
resetMemoryDatabaseInstance()
} else if (currentSimpleConfig !== previousSimpleConfig) {
resetMemoryDatabaseInstance()
}
if (typeof ChatGPTConfig._triggerSave === 'function') {
ChatGPTConfig._triggerSave('memory')
}
return ChatGPTConfig.memory
}
export const MemoryRouter = (() => {
const router = express.Router()
router.get('/config', (_req, res) => {
res.status(200).json(ChaiteResponse.ok(ChatGPTConfig.memory))
})
router.post('/config', (req, res) => {
try {
const updated = updateMemoryConfig(req.body || {})
res.status(200).json(ChaiteResponse.ok(updated))
} catch (error) {
logger.error('Failed to update memory config:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to update memory config'))
}
})
router.get('/group/:groupId/facts', (req, res) => {
const { groupId } = req.params
const limit = parsePositiveInt(req.query.limit, 50)
const offset = parsePositiveInt(req.query.offset, 0)
try {
const facts = memoryService.listGroupFacts(groupId, limit, offset)
res.status(200).json(ChaiteResponse.ok(facts))
} catch (error) {
logger.error('Failed to fetch group facts:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to fetch group facts'))
}
})
router.get('/extensions/simple/status', (_req, res) => {
try {
logger?.debug?.('[Memory] simple extension status requested')
const state = getSimpleExtensionState()
const simpleConfig = ChatGPTConfig.memory?.extensions?.simple || {}
const libraryPath = simpleConfig.libraryPath || state.libraryPath || ''
const dictPath = simpleConfig.dictPath || state.dictPath || ''
const resolvedLibraryPath = libraryPath ? resolvePluginPath(libraryPath) : ''
const resolvedDictPath = dictPath ? resolvePluginPath(dictPath) : ''
res.status(200).json(ChaiteResponse.ok({
...state,
enabled: Boolean(simpleConfig.enable),
libraryPath,
dictPath,
platform: process.platform,
arch: process.arch,
resolvedLibraryPath,
libraryExists: resolvedLibraryPath ? fs.existsSync(resolvedLibraryPath) : false,
resolvedDictPath,
dictExists: resolvedDictPath ? fs.existsSync(resolvedDictPath) : false
}))
} catch (error) {
logger.error('Failed to read simple extension status:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to read simple extension status'))
}
})
router.post('/extensions/simple/download', async (req, res) => {
const { assetKey, assetName, installDir } = req.body || {}
try {
const resolvedAsset = resolveSimpleAsset(assetKey, assetName)
if (!resolvedAsset.asset) {
res.status(400).json(ChaiteResponse.fail(null, '无法确定当前平台的扩展文件,请手动指定 assetName。'))
return
}
logger?.info?.('[Memory] downloading simple extension asset=%s (key=%s)', resolvedAsset.asset, resolvedAsset.key)
const targetRelativeDir = installDir || path.join(DEFAULT_SIMPLE_INSTALL_DIR, resolvedAsset.key || 'downloaded')
const targetDir = resolvePluginPath(targetRelativeDir)
const result = await downloadSimpleExtensionArchive({
assetKey: resolvedAsset.key || assetKey || 'custom',
assetName: resolvedAsset.asset,
targetDir
})
resetMemoryDatabaseInstance()
logger?.info?.('[Memory] simple extension downloaded and memory DB scheduled for reload')
res.status(200).json(ChaiteResponse.ok({
...result,
assetName: resolvedAsset.asset,
assetKey: resolvedAsset.key || assetKey || 'custom'
}))
} catch (error) {
logger.error('Failed to download simple extension:', error)
res.status(500).json(ChaiteResponse.fail(null, error?.message || 'Failed to download simple extension'))
}
})
router.post('/group/:groupId/facts', async (req, res) => {
const { groupId } = req.params
const facts = Array.isArray(req.body?.facts) ? req.body.facts : []
if (facts.length === 0) {
res.status(400).json(ChaiteResponse.fail(null, 'facts is required'))
return
}
try {
const saved = await memoryService.saveGroupFacts(groupId, facts)
res.status(200).json(ChaiteResponse.ok(saved))
} catch (error) {
logger.error('Failed to save group facts:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to save group facts'))
}
})
router.post('/group/:groupId/query', async (req, res) => {
const { groupId } = req.params
const { query, limit, minImportance } = req.body || {}
if (!query || typeof query !== 'string') {
res.status(400).json(ChaiteResponse.fail(null, 'query is required'))
return
}
try {
const facts = await memoryService.queryGroupFacts(groupId, query, {
limit: parsePositiveInt(limit, undefined),
minImportance: minImportance !== undefined ? parseNumber(minImportance, undefined) : undefined
})
res.status(200).json(ChaiteResponse.ok(facts))
} catch (error) {
logger.error('Failed to query group memory:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to query group memory'))
}
})
router.delete('/group/:groupId/facts/:factId', (req, res) => {
const { groupId, factId } = req.params
try {
const removed = memoryService.deleteGroupFact(groupId, factId)
if (!removed) {
res.status(404).json(ChaiteResponse.fail(null, 'Fact not found'))
return
}
res.status(200).json(ChaiteResponse.ok({ removed }))
} catch (error) {
logger.error('Failed to delete group fact:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to delete group fact'))
}
})
router.get('/user/memories', (req, res) => {
const userId = parseOptionalStringParam(req.query.userId)
const groupId = parseOptionalStringParam(req.query.groupId)
const limit = parsePositiveInt(req.query.limit, 50)
const offset = parsePositiveInt(req.query.offset, 0)
try {
const memories = memoryService.listUserMemories(userId, groupId, limit, offset)
res.status(200).json(ChaiteResponse.ok(memories))
} catch (error) {
logger.error('Failed to fetch user memories:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to fetch user memories'))
}
})
router.get('/user/:userId/memories', (req, res) => {
const { userId } = req.params
const groupId = req.query.groupId ?? null
const limit = parsePositiveInt(req.query.limit, 50)
const offset = parsePositiveInt(req.query.offset, 0)
try {
const memories = memoryService.listUserMemories(userId, groupId, limit, offset)
res.status(200).json(ChaiteResponse.ok(memories))
} catch (error) {
logger.error('Failed to fetch user memories:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to fetch user memories'))
}
})
router.post('/user/:userId/query', (req, res) => {
const { userId } = req.params
const groupId = req.body?.groupId ?? req.query.groupId ?? null
const query = req.body?.query
const totalLimit = parsePositiveInt(req.body?.totalLimit, undefined)
const searchLimit = parsePositiveInt(req.body?.searchLimit, undefined)
const minImportance = req.body?.minImportance !== undefined
? parseNumber(req.body.minImportance, undefined)
: undefined
if (!query || typeof query !== 'string') {
res.status(400).json(ChaiteResponse.fail(null, 'query is required'))
return
}
try {
const memories = memoryService.queryUserMemories(userId, groupId, query, {
totalLimit,
searchLimit,
minImportance
})
res.status(200).json(ChaiteResponse.ok(memories))
} catch (error) {
logger.error('Failed to query user memory:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to query user memory'))
}
})
router.post('/user/:userId/memories', (req, res) => {
const { userId } = req.params
const groupId = req.body?.groupId ?? null
const memories = Array.isArray(req.body?.memories) ? req.body.memories : []
if (memories.length === 0) {
res.status(400).json(ChaiteResponse.fail(null, 'memories is required'))
return
}
try {
const updated = memoryService.upsertUserMemories(userId, groupId, memories)
res.status(200).json(ChaiteResponse.ok({ updated }))
} catch (error) {
logger.error('Failed to upsert user memories:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to upsert user memories'))
}
})
router.delete('/user/:userId/memories/:memoryId', (req, res) => {
const { userId, memoryId } = req.params
try {
const removed = memoryService.deleteUserMemory(memoryId, userId)
if (!removed) {
res.status(404).json(ChaiteResponse.fail(null, 'Memory not found'))
return
}
res.status(200).json(ChaiteResponse.ok({ removed }))
} catch (error) {
logger.error('Failed to delete user memory:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to delete user memory'))
}
})
router.delete('/memories/:memoryId', (req, res) => {
const { memoryId } = req.params
try {
const removed = memoryService.deleteUserMemory(memoryId)
if (!removed) {
res.status(404).json(ChaiteResponse.fail(null, 'Memory not found'))
return
}
res.status(200).json(ChaiteResponse.ok({ removed }))
} catch (error) {
logger.error('Failed to delete memory:', error)
res.status(500).json(ChaiteResponse.fail(null, 'Failed to delete memory'))
}
})
return router
})()

194
models/memory/service.js Normal file
View file

@ -0,0 +1,194 @@
import ChatGPTConfig from '../../config/config.js'
import { getMemoryDatabase } from './database.js'
import { GroupMemoryStore } from './groupMemoryStore.js'
import { UserMemoryStore } from './userMemoryStore.js'
function normaliseId (id) {
if (id === null || id === undefined) {
return ''
}
return String(id)
}
function formatEntry (entry) {
let str = ''
try {
str = JSON.stringify(entry)
} catch (err) {
str = String(entry)
}
const limit = 200
return str.length > limit ? str.slice(0, limit) + '…' : str
}
function normalisePersonalMemory (entry) {
if (!entry) return null
let text = ''
let importance = typeof entry?.importance === 'number' ? entry.importance : 0.6
let sourceId = entry?.source_message_id ? String(entry.source_message_id) : null
if (typeof entry === 'string') {
text = entry.trim()
} else if (typeof entry === 'object') {
const value = entry.value || entry.text || entry.fact || entry.sentence
if (Array.isArray(value)) {
text = value.join(', ').trim()
} else if (value) {
text = String(value).trim()
}
if (entry.importance !== undefined) {
importance = Number(entry.importance)
}
if (entry.source_message_id) {
sourceId = String(entry.source_message_id)
}
}
if (!text) {
return null
}
if (Number.isNaN(importance) || importance <= 0) {
importance = 0.6
}
return { text, importance, sourceId }
}
class MemoryService {
constructor () {
const db = getMemoryDatabase()
this.groupStore = new GroupMemoryStore(db)
this.userStore = new UserMemoryStore(db)
}
isGroupMemoryEnabled (groupId) {
const config = ChatGPTConfig.memory?.group
if (!config?.enable) {
return false
}
const enabledGroups = (config.enabledGroups || []).map(normaliseId)
if (enabledGroups.length === 0) {
return false
}
return enabledGroups.includes(normaliseId(groupId))
}
isUserMemoryEnabled (userId) {
const config = ChatGPTConfig.memory?.user
if (!config?.enable) {
return false
}
const uid = normaliseId(userId)
const whitelist = (config.whitelist || []).map(normaliseId).filter(Boolean)
const blacklist = (config.blacklist || []).map(normaliseId).filter(Boolean)
if (whitelist.length > 0) {
return whitelist.includes(uid)
}
if (blacklist.length > 0) {
return !blacklist.includes(uid)
}
return true
}
async saveGroupFacts (groupId, facts) {
if (!this.isGroupMemoryEnabled(groupId)) {
return []
}
try {
const saved = await this.groupStore.saveFacts(groupId, facts)
if (saved.length > 0) {
logger.info(`[Memory] group=${groupId} stored ${saved.length} facts`)
saved.slice(0, 10).forEach((item, idx) => {
logger.debug(`[Memory] group stored fact[${idx}] ${formatEntry(item)}`)
})
}
return saved
} catch (err) {
logger.error('Failed to save group facts:', err)
return []
}
}
async queryGroupFacts (groupId, queryText, options = {}) {
if (!this.isGroupMemoryEnabled(groupId)) {
return []
}
const { maxFactsPerInjection = 5, minImportanceForInjection = 0 } = ChatGPTConfig.memory?.group || {}
const limit = options.limit || maxFactsPerInjection
const minImportance = options.minImportance ?? minImportanceForInjection
try {
return await this.groupStore.queryRelevantFacts(groupId, queryText, { limit, minImportance })
} catch (err) {
logger.error('Failed to query group memory:', err)
return []
}
}
listGroupFacts (groupId, limit = 50, offset = 0) {
return this.groupStore.listFacts(groupId, limit, offset)
}
deleteGroupFact (groupId, factId) {
return this.groupStore.deleteFact(groupId, factId)
}
upsertUserMemories (userId, groupId, memories) {
if (!this.isUserMemoryEnabled(userId)) {
return 0
}
try {
const prepared = (memories || [])
.map(normalisePersonalMemory)
.filter(item => item && item.text)
.map(item => ({
value: item.text,
importance: item.importance,
source_message_id: item.sourceId
}))
if (prepared.length === 0) {
return 0
}
const changed = this.userStore.upsertMemories(userId, groupId, prepared)
if (changed > 0) {
logger.info(`[Memory] user=${userId} updated ${changed} personal memories${groupId ? ` in group=${groupId}` : ''}`)
prepared.slice(0, 10).forEach((item, idx) => {
logger.debug(`[Memory] user memory upsert[${idx}] ${formatEntry(item)}`)
})
}
return changed
} catch (err) {
logger.error('Failed to upsert user memories:', err)
return 0
}
}
queryUserMemories (userId, groupId = null, queryText = '', options = {}) {
if (!this.isUserMemoryEnabled(userId)) {
return []
}
const userConfig = ChatGPTConfig.memory?.user || {}
const totalLimit = options.totalLimit ?? userConfig.maxItemsPerInjection ?? 5
const searchLimit = options.searchLimit ?? userConfig.maxRelevantItemsPerQuery ?? totalLimit
const minImportance = options.minImportance ?? userConfig.minImportanceForInjection ?? 0
if (!totalLimit || totalLimit <= 0) {
return []
}
try {
return this.userStore.queryMemories(userId, groupId, queryText, {
limit: searchLimit,
fallbackLimit: totalLimit,
minImportance
})
} catch (err) {
logger.error('Failed to query user memories:', err)
return []
}
}
listUserMemories (userId, groupId = null, limit = 50, offset = 0) {
return this.userStore.listUserMemories(userId, groupId, limit, offset)
}
deleteUserMemory (memoryId, userId = null) {
return this.userStore.deleteMemoryById(memoryId, userId)
}
}
export const memoryService = new MemoryService()

View file

@ -0,0 +1,129 @@
import { Chaite } from 'chaite'
import * as crypto from 'node:crypto'
import { extractUserMemories } from './extractor.js'
import { memoryService } from './service.js'
const USER_MEMORY_CONTEXT_LIMIT = 6
export function extractTextFromContents (contents) {
if (!Array.isArray(contents)) {
return ''
}
return contents
.filter(item => item && item.type === 'text')
.map(item => item.text || '')
.join('\n')
.trim()
}
export function extractTextFromUserMessage (userMessage) {
if (!userMessage?.content) {
return ''
}
return userMessage.content
.filter(item => item.type === 'text')
.map(item => item.text || '')
.join('\n')
.trim()
}
function normaliseMemoriesInput (memories, sourceId) {
return (memories || []).map(mem => {
if (typeof mem === 'string') {
return {
value: mem,
source_message_id: sourceId
}
}
if (mem && typeof mem === 'object') {
const cloned = { ...mem }
if (!cloned.source_message_id && sourceId) {
cloned.source_message_id = sourceId
}
if (!cloned.value && cloned.fact) {
cloned.value = cloned.fact
}
if (!cloned.value && cloned.text) {
cloned.value = cloned.text
}
return cloned
}
return {
value: String(mem),
source_message_id: sourceId
}
})
}
export async function processUserMemory ({ event, userMessage, userText, conversationId, assistantContents, assistantMessageId }) {
const e = event
if (!memoryService.isUserMemoryEnabled(e.sender.user_id)) {
return
}
const snippets = []
const userMessageId = e.message_id || e.seq || userMessage?.id || crypto.randomUUID()
const senderName = e.sender?.card || e.sender?.nickname || String(e.sender?.user_id || '')
try {
const historyManager = Chaite.getInstance()?.getHistoryManager?.()
if (historyManager && conversationId) {
const history = await historyManager.getHistory(null, conversationId)
const filtered = (history || [])
.filter(msg => ['user', 'assistant'].includes(msg.role))
.map(msg => ({
role: msg.role,
text: extractTextFromContents(msg.content),
nickname: msg.role === 'user' ? senderName : '机器人',
message_id: msg.id
}))
.filter(item => item.text)
if (filtered.length > 0) {
const limited = filtered.slice(-USER_MEMORY_CONTEXT_LIMIT * 2)
snippets.push(...limited)
}
}
} catch (err) {
logger.warn('Failed to collect user memory context:', err)
}
if (assistantContents) {
const assistantText = extractTextFromContents(assistantContents)
if (assistantText) {
snippets.push({
role: 'assistant',
text: assistantText,
nickname: '机器人',
message_id: assistantMessageId || crypto.randomUUID()
})
}
}
if (userText && !snippets.some(item => item.message_id === userMessageId)) {
snippets.push({
role: 'user',
text: userText,
nickname: senderName,
message_id: userMessageId
})
}
if (snippets.length === 0) {
return
}
const existingRecords = memoryService.listUserMemories(e.sender.user_id, e.isGroup ? e.group_id : null, 50)
const existingTexts = existingRecords.map(record => record.value).filter(Boolean)
const memories = await extractUserMemories(snippets, existingTexts)
if (!memories || memories.length === 0) {
return
}
const enriched = normaliseMemoriesInput(memories, userMessageId)
memoryService.upsertUserMemories(
e.sender.user_id,
e.isGroup ? e.group_id : null,
enriched
)
}
export { USER_MEMORY_CONTEXT_LIMIT }

View file

@ -0,0 +1,335 @@
import { getMemoryDatabase, getUserMemoryFtsConfig, sanitiseFtsQueryInput } from './database.js'
import { md5 } from '../../utils/common.js'
function normaliseId (value) {
if (value === null || value === undefined) {
return null
}
const str = String(value).trim()
if (!str || str.toLowerCase() === 'null' || str.toLowerCase() === 'undefined') {
return null
}
return str
}
function toMemoryPayload (entry) {
if (entry === null || entry === undefined) {
return null
}
if (typeof entry === 'string') {
const text = entry.trim()
return text ? { value: text, importance: 0.5 } : null
}
if (typeof entry === 'object') {
const rawValue = entry.value ?? entry.text ?? entry.fact ?? ''
const value = typeof rawValue === 'string' ? rawValue.trim() : String(rawValue || '').trim()
if (!value) {
return null
}
const importance = typeof entry.importance === 'number' ? entry.importance : 0.5
const sourceId = entry.source_message_id ? String(entry.source_message_id) : null
const providedKey = entry.key ? String(entry.key).trim() : ''
return {
value,
importance,
source_message_id: sourceId,
providedKey
}
}
const value = String(entry).trim()
return value ? { value, importance: 0.5 } : null
}
function deriveKey (value, providedKey = '') {
const trimmedProvided = providedKey?.trim?.() || ''
if (trimmedProvided) {
return trimmedProvided
}
if (!value) {
return null
}
return `fact:${md5(String(value))}`
}
function stripKey (row) {
if (!row || typeof row !== 'object') {
return row
}
const { key, ...rest } = row
return rest
}
function appendRows (target, rows, seen) {
if (!Array.isArray(rows)) {
return
}
for (const row of rows) {
if (!row || seen.has(row.id)) {
continue
}
target.push(stripKey(row))
seen.add(row.id)
}
}
export class UserMemoryStore {
constructor (db = getMemoryDatabase()) {
this.resetDatabase(db)
}
resetDatabase (db = getMemoryDatabase()) {
this.db = db
this.upsertStmt = this.db.prepare(`
INSERT INTO user_memory (user_id, group_id, key, value, importance, source_message_id, created_at, updated_at)
VALUES (@user_id, @group_id, @key, @value, @importance, @source_message_id, datetime('now'), datetime('now'))
ON CONFLICT(user_id, coalesce(group_id, ''), key) DO UPDATE SET
value = excluded.value,
importance = excluded.importance,
source_message_id = excluded.source_message_id,
updated_at = datetime('now')
`)
}
ensureDb () {
if (!this.db || this.db.open === false) {
logger?.debug?.('[Memory] refreshing user memory database connection')
this.resetDatabase()
}
return this.db
}
upsertMemories (userId, groupId, memories) {
if (!memories || memories.length === 0) {
return 0
}
this.ensureDb()
const normUserId = normaliseId(userId)
const normGroupId = normaliseId(groupId)
const prepared = (memories || [])
.map(toMemoryPayload)
.filter(item => item && item.value)
.map(item => {
const key = deriveKey(item.value, item.providedKey)
if (!key) {
return null
}
return {
user_id: normUserId,
group_id: normGroupId,
key,
value: String(item.value),
importance: typeof item.importance === 'number' ? item.importance : 0.5,
source_message_id: item.source_message_id ? String(item.source_message_id) : null
}
})
.filter(Boolean)
if (!prepared.length) {
return 0
}
const transaction = this.db.transaction(items => {
let changes = 0
for (const item of items) {
const info = this.upsertStmt.run(item)
changes += info.changes
}
return changes
})
return transaction(prepared)
}
listUserMemories (userId = null, groupId = null, limit = 50, offset = 0) {
this.ensureDb()
const normUserId = normaliseId(userId)
const normGroupId = normaliseId(groupId)
const params = []
let query = `
SELECT * FROM user_memory
WHERE 1 = 1
`
if (normUserId) {
query += ' AND user_id = ?'
params.push(normUserId)
}
if (normGroupId) {
if (normUserId) {
query += ' AND (group_id = ? OR group_id IS NULL)'
} else {
query += ' AND group_id = ?'
}
params.push(normGroupId)
}
query += `
ORDER BY importance DESC, updated_at DESC
LIMIT ? OFFSET ?
`
params.push(limit, offset)
const rows = this.db.prepare(query).all(...params)
return rows.map(stripKey)
}
deleteMemoryById (memoryId, userId = null) {
this.ensureDb()
if (userId) {
const result = this.db.prepare('DELETE FROM user_memory WHERE id = ? AND user_id = ?').run(memoryId, normaliseId(userId))
return result.changes > 0
}
const result = this.db.prepare('DELETE FROM user_memory WHERE id = ?').run(memoryId)
return result.changes > 0
}
listRecentMemories (userId, groupId = null, limit = 50, excludeIds = [], minImportance = 0) {
this.ensureDb()
const normUserId = normaliseId(userId)
const normGroupId = normaliseId(groupId)
const filteredExclude = (excludeIds || []).filter(Boolean)
const params = [normUserId]
let query = `
SELECT * FROM user_memory
WHERE user_id = ?
AND importance >= ?
`
params.push(minImportance)
if (normGroupId) {
query += ' AND (group_id = ? OR group_id IS NULL)'
params.push(normGroupId)
}
if (filteredExclude.length) {
query += ` AND id NOT IN (${filteredExclude.map(() => '?').join(',')})`
params.push(...filteredExclude)
}
query += `
ORDER BY updated_at DESC
LIMIT ?
`
params.push(limit)
return this.db.prepare(query).all(...params).map(stripKey)
}
textSearch (userId, groupId = null, queryText, limit = 5, excludeIds = []) {
if (!queryText || !queryText.trim()) {
return []
}
this.ensureDb()
const normUserId = normaliseId(userId)
const normGroupId = normaliseId(groupId)
const filteredExclude = (excludeIds || []).filter(Boolean)
const originalQuery = queryText.trim()
const ftsConfig = getUserMemoryFtsConfig()
const matchQueryParam = sanitiseFtsQueryInput(originalQuery, ftsConfig)
const results = []
const seen = new Set(filteredExclude)
if (matchQueryParam) {
const matchExpression = ftsConfig.matchQuery ? `${ftsConfig.matchQuery}(?)` : '?'
const params = [normUserId, matchQueryParam]
let query = `
SELECT um.*, bm25(user_memory_fts) AS bm25_score
FROM user_memory_fts
JOIN user_memory um ON um.id = user_memory_fts.rowid
WHERE um.user_id = ?
AND user_memory_fts MATCH ${matchExpression}
`
if (normGroupId) {
query += ' AND (um.group_id = ? OR um.group_id IS NULL)'
params.push(normGroupId)
}
if (filteredExclude.length) {
query += ` AND um.id NOT IN (${filteredExclude.map(() => '?').join(',')})`
params.push(...filteredExclude)
}
query += `
ORDER BY bm25_score ASC, um.updated_at DESC
LIMIT ?
`
params.push(limit)
try {
const ftsRows = this.db.prepare(query).all(...params)
appendRows(results, ftsRows, seen)
} catch (err) {
logger?.warn?.('User memory text search failed:', err)
}
} else {
logger?.debug?.('[Memory] user memory text search skipped MATCH due to empty query after sanitisation')
}
if (results.length < limit) {
const likeParams = [normUserId, originalQuery]
let likeQuery = `
SELECT um.*
FROM user_memory um
WHERE um.user_id = ?
AND instr(um.value, ?) > 0
`
if (normGroupId) {
likeQuery += ' AND (um.group_id = ? OR um.group_id IS NULL)'
likeParams.push(normGroupId)
}
if (filteredExclude.length) {
likeQuery += ` AND um.id NOT IN (${filteredExclude.map(() => '?').join(',')})`
likeParams.push(...filteredExclude)
}
likeQuery += `
ORDER BY um.importance DESC, um.updated_at DESC
LIMIT ?
`
likeParams.push(Math.max(limit * 2, limit))
try {
const likeRows = this.db.prepare(likeQuery).all(...likeParams)
appendRows(results, likeRows, seen)
} catch (err) {
logger?.warn?.('User memory LIKE search failed:', err)
}
}
return results.slice(0, limit)
}
queryMemories (userId, groupId = null, queryText = '', options = {}) {
const normUserId = normaliseId(userId)
if (!normUserId) {
return []
}
this.ensureDb()
const {
limit = 3,
fallbackLimit,
minImportance = 0
} = options
const totalLimit = Math.max(0, fallbackLimit ?? limit ?? 0)
if (totalLimit === 0) {
return []
}
const searchLimit = limit > 0 ? Math.min(limit, totalLimit) : totalLimit
const results = []
const seen = new Set()
const append = rows => {
for (const row of rows || []) {
if (!row || seen.has(row.id)) {
continue
}
results.push(row)
seen.add(row.id)
if (results.length >= totalLimit) {
break
}
}
}
if (queryText && searchLimit > 0) {
const searched = this.textSearch(userId, groupId, queryText, searchLimit)
append(searched)
}
if (results.length < totalLimit) {
const recent = this.listRecentMemories(
userId,
groupId,
Math.max(totalLimit * 2, totalLimit),
Array.from(seen),
minImportance
)
append(recent)
}
return results.slice(0, totalLimit)
}
}

View file

@ -1,26 +1,21 @@
{
"name": "chatgpt-plugin",
"version": "3.0.0",
"type": "module",
"author": "ikechan8370",
"dependencies": {
"@waylaidwanderer/chatgpt-api": "^1.32.0",
"chatgpt": "^5.1.1",
"delay": "^5.0.0",
"https-proxy-agent": "5.0.1",
"keyv": "^4.5.2",
"keyv-file": "^0.2.0",
"node-fetch": "^3.3.1",
"openai": "^3.2.1",
"random": "^4.1.0",
"undici": "^5.21.0",
"uuid": "^9.0.0",
"ws": "^8.13.0"
"better-sqlite3": "^9.4.3",
"adm-zip": "^0.5.10",
"chaite": "^1.8.2",
"js-yaml": "^4.1.0",
"keyv": "^5.3.1",
"keyv-file": "^5.1.2",
"lowdb": "^7.0.1",
"sqlite-vec": "^0.1.7-alpha.2",
"vectra": "^0.9.0"
},
"optionalDependencies": {
"jimp": "^0.22.7",
"puppeteer-extra": "^3.3.6",
"puppeteer-extra-plugin-recaptcha": "^3.6.8",
"puppeteer-extra-plugin-stealth": "^2.11.2",
"sharp": "^0.31.3"
}
}
"peerDependencies": {
"sqlite3": ">=5.1.6"
},
"pnpm": {}
}

View file

View file

@ -1,270 +0,0 @@
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

View file

@ -1,630 +0,0 @@
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hmiqojjg.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hviqojjg.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hniqojjg.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hoiqojjg.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hkiqojjg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hliqojjg.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hriqm.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0udc1uaw.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0ddc1uaw.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0vdc1uaw.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0adc1uaw.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0wdc1uaw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0xdc1uaw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0zdc0.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhmiqojjg.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhviqojjg.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhniqojjg.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhoiqojjg.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhkiqojjg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhliqojjg.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhriqm.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhmiqojjg.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhviqojjg.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhniqojjg.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhoiqojjg.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhkiqojjg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhliqojjg.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhriqm.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hmiqojjg.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hviqojjg.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hniqojjg.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hoiqojjg.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hkiqojjg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hliqojjg.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hriqm.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8ox-hpoqc.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8ovuhpoqc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8oxuhpoqc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8ouehpoqc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8oxehpoqc.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8oxohpoqc.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8ouuhp.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufwj0bbck.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufuz0bbck.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufwz0bbck.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufvp0bbck.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufwp0bbck.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufw50bbck.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufvz0b.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkox-hpoqc.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkovuhpoqc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkoxuhpoqc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkouehpoqc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkoxehpoqc.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkoxohpoqc.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkouuhp.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgox-hpoqc.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgovuhpoqc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgoxuhpoqc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgouehpoqc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgoxehpoqc.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgoxohpoqc.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgouuhp.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsox-hpoqc.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsovuhpoqc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsoxuhpoqc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsouehpoqc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsoxehpoqc.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsoxohpoqc.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsouuhp.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

View file

@ -1,144 +0,0 @@
<!doctype html>
<html class="no-js" lang="zxx">
<head>
<!--========= Required meta tags =========-->
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<!--====== CSS Here ======-->
<link rel="stylesheet" href="{{pluResPath}}content/static/css/bootstrap.min.css">
<link rel="stylesheet" href="{{pluResPath}}content/static/css/font-awesome.min.css">
<link rel="stylesheet" href="{{pluResPath}}content/static/css/hljs.css">
<link rel="stylesheet" href="{{pluResPath}}content/Bing/style.css">
</head>
<body class="body-{{style}}">
<header class="site-header">
<div class="container">
<div class="row">
<div class="col-lg-3 col-4 my-auto">
<a href="#" class="site-logo">
<img src="{{pluResPath}}content/static/picture/bing.png" alt="LOGO">
</a>
</div>
</div>
</div>
</header>
<section class="about-area pt-232">
<div class="container">
<div class="row justify-content-end">
<div class="col-xl-5 col-lg-5 text-right">
<div class="section-heading section-heading-{{style}}">
<h2>New Bing</h2>
{{if cache.file != ''}}
<p> {{cache.file}} </p>
{{/if}}
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="hero-content hero-content-{{style}}">
<h4>{{senderName}}</h4>
</div>
<div class="about-content">
<p class="markdown_prompt"></p>
<span class="height-50"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="hero-content hero-content-{{style}}">
{{if style === 'Sydney'}}
<h4>Sydney</h4>
{{else}}
<h4>必应</h4>
{{/if}}
</div>
<div class="about-content">
<p class="markdown_content"></p>
<span class="height-50"></span>
</div>
</div>
</div>
{{if quote}}
<div class="row">
<div class="col-xl-12">
<div class="hero-content hero-content-{{style}}">
<h4>引用</h4>
</div>
<div class="about-content">
{{each quotes item}}
<p>{{item}}</p>
{{/each}}
<span class="height-50"></span>
</div>
</div>
</div>
{{/if}}
{{if cache.file != ''}}
<div id="qrcode" class="row justify-content-end"></div>
{{/if}}
</div>
</section>
<!-- footer start -->
<footer class="site-footer site-footer-{{style}} mt-175">
<div class="container">
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-10 my-auto text-right">
<div class="copyright-text copyright-text-{{style}}">
<p>Response to {{senderName}} Created By Yunzai-Bot and ChatGPT-Plugin {{version}}</a></p>
</div>
</div>
</div>
</div>
</footer>
<!-- footer end -->
<!--========= JS Here =========-->
<script>
MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']]
}
};
</script>
<script src="{{pluResPath}}content/static/js/jquery-2.2.4.min.js"></script>
<script src="{{pluResPath}}content/static/js/jquery.qrcode.min.js"></script>
<script src="{{pluResPath}}content/static/js/highlight.min.js"></script>
<script src="{{pluResPath}}content/static/js/marked.min.js"></script>
<script src="{{pluResPath}}content/static/js/tex-mml-chtml.js"></script>
<script src="{{pluResPath}}content/static/js/base64.min.js"></script>
<script src="{{pluResPath}}content/static/js/main.js"></script>
<script src="{{pluResPath}}content/static/js/purify.min.js"></script>
<script>
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
highlight: function (code,lang) {
return hljs.highlightAuto(code,[lang]).value;
}
});
const markdown_content = '{{@ content}}';
const html_content = marked.parse(Base64.decode(markdown_content));
const markdown_prompt = '{{@ prompt}}';
const html_prompt = marked.parse(Base64.decode(markdown_prompt));
$(".markdown_content").html(DOMPurify.sanitize(html_content));
$(".markdown_prompt").html(DOMPurify.sanitize(html_prompt));
jQuery('#qrcode').qrcode({width: 128,height: 128,text: "{{cache.cacheUrl}}/{{cache.file}}"});
</script>
</body>
</html>

File diff suppressed because it is too large Load diff

View file

@ -1,270 +0,0 @@
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* vietnamese */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Josefin Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

View file

@ -1,630 +0,0 @@
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hmiqojjg.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hviqojjg.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hniqojjg.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hoiqojjg.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hkiqojjg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hliqojjg.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 300;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwyv9hriqm.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0udc1uaw.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0ddc1uaw.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0vdc1uaw.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0adc1uaw.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0wdc1uaw.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0xdc1uaw.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem6yags126mizpba-ufuk0zdc0.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhmiqojjg.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhviqojjg.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhniqojjg.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhoiqojjg.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhkiqojjg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhliqojjg.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 600;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukxgudhriqm.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhmiqojjg.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhviqojjg.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhniqojjg.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhoiqojjg.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhkiqojjg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhliqojjg.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 700;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukwiunhriqm.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hmiqojjg.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hviqojjg.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hniqojjg.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hoiqojjg.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hkiqojjg.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hliqojjg.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: italic;
font-weight: 800;
font-display: swap;
src: url(../fonts/memnyags126mizpba-ufukw-u9hriqm.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8ox-hpoqc.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8ovuhpoqc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8oxuhpoqc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8ouehpoqc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8oxehpoqc.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8oxohpoqc.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un_r8ouuhp.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufwj0bbck.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufuz0bbck.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufwz0bbck.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufvp0bbck.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufwp0bbck.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufw50bbck.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(../fonts/mem8yags126mizpba-ufvz0b.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkox-hpoqc.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkovuhpoqc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkoxuhpoqc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkouehpoqc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkoxehpoqc.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkoxohpoqc.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-unirkouuhp.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgox-hpoqc.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgovuhpoqc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgoxuhpoqc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgouehpoqc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgoxehpoqc.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgoxohpoqc.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un7rgouuhp.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsox-hpoqc.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsovuhpoqc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsoxuhpoqc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsouehpoqc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsoxehpoqc.woff2) format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsoxohpoqc.woff2) format('woff2');
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url(../fonts/mem5yags126mizpba-un8rsouuhp.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

View file

@ -1,126 +0,0 @@
<!doctype html>
<html class="no-js" lang="zxx">
<head>
<!--========= Required meta tags =========-->
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<!--====== CSS Here ======-->
<link rel="stylesheet" href="{{pluResPath}}content/static/css/bootstrap.min.css">
<link rel="stylesheet" href="{{pluResPath}}content/static/css/font-awesome.min.css">
<link rel="stylesheet" href="{{pluResPath}}content/static/css/hljs.css">
<link rel="stylesheet" href="{{pluResPath}}content/ChatGPT/style.css">
</head>
<body>
<header class="site-header">
<div class="container">
<div class="row">
<div class="col-lg-3 col-4 my-auto">
<a href="#" class="site-logo">
<img src="{{pluResPath}}content/static/picture/openai.png" alt="LOGO">
</a>
</div>
</div>
</div>
</header>
<section class="about-area pt-232">
<div class="container">
<div class="row justify-content-end">
<div class="col-xl-5 col-lg-5 text-right">
<div class="section-heading">
<h2>Open AI</h2>
{{if cache.file != ''}}
<p> {{cache.file}} </p>
{{/if}}
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="hero-content">
<h4>{{senderName}}</h4>
</div>
<div class="about-content">
<p class="markdown_prompt"></p>
<span class="height-50"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="hero-content">
<h4>ChatGPT</h4>
</div>
<div class="about-content">
<p class="markdown_content"></p>
<span class="height-50"></span>
</div>
</div>
</div>
{{if cache.file != ''}}
<div id="qrcode" class="row justify-content-end"></div>
{{/if}}
</div>
</section>
<!-- footer start -->
<footer class="site-footer mt-175">
<div class="container">
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-10 my-auto text-right">
<div class="copyright-text">
<p>Response to {{senderName}} Created By Yunzai-Bot and ChatGPT-Plugin {{version}}</a></p>
</div>
</div>
</div>
</div>
</footer>
<!-- footer end -->
<!--========= JS Here =========-->
<script>
MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']]
}
};
</script>
<script src="{{pluResPath}}content/static/js/jquery-2.2.4.min.js"></script>
<script src="{{pluResPath}}content/static/js/jquery.qrcode.min.js"></script>
<script src="{{pluResPath}}content/static/js/highlight.min.js"></script>
<script src="{{pluResPath}}content/static/js/marked.min.js"></script>
<script src="{{pluResPath}}content/static/js/tex-mml-chtml.js"></script>
<script src="{{pluResPath}}content/static/js/base64.min.js"></script>
<script src="{{pluResPath}}content/static/js/main.js"></script>
<script src="{{pluResPath}}content/static/js/purify.min.js"></script>
<script>
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
highlight: function (code,lang) {
return hljs.highlightAuto(code,[lang]).value;
}
});
const markdown_content = '{{@ content}}';
const html_content = marked.parse(Base64.decode(markdown_content));
const markdown_prompt = '{{@ prompt}}';
const html_prompt = marked.parse(Base64.decode(markdown_prompt));
$(".markdown_content").html(DOMPurify.sanitize(html_content));
$(".markdown_prompt").html(DOMPurify.sanitize(html_prompt));
jQuery('#qrcode').qrcode({width: 128,height: 128,text: "{{cache.cacheUrl}}/{{cache.file}}"});
</script>
</body>
</html>

View file

@ -1,429 +0,0 @@
@charset "UTF-8";
/*-----------------------------------------------------------------------------------
Template Name: Aiden - Creative Portfolio HTML5 Template
Template URI: site.com
Description: Aiden - Creative Portfolio HTML5 Template
Author: Rs_Theme
Version: 1.0
-----------------------------------------------------------------------------------
CSS INDEX
===================
01. Theme default css
02. header css
03. Navigation css
04. hero css
05. about css
06. service css
07. work CSS
08. testimonial css
09. brand css
10. blog css
11. contact css
12. breadcrumb css
13. cta css
14. contact-page css
15. blog-page css
16. footer css
-----------------------------------------------------------------------------------*/
/* reset css start */
@import url("644b614f82934cd2a7833c108ceb941b.css");
@import url("a0020bf6401d4e99884e2be5f5402f24.css");
html {
scroll-behavior: smooth;
}
body {
font-family: "Microsoft YaHei", "微软雅黑", "Josefin Sans", sans-serif;
font-size: 18px;
padding: 0;
margin: 0;
font-weight: 400;
position: relative;
line-height: 26px;
background: #f5feff;
}
img {
max-width: 100%;
height: auto;
}
ul, ol {
padding: 0;
margin: 0;
list-style: none;
}
button {
cursor: pointer;
}
*:focus {
outline: none;
}
button {
border: none;
-webkit-transition: 0.3s;
-o-transition: 0.3s;
transition: 0.3s;
}
button:focus {
outline: none;
}
a {
-webkit-transition: 0.3s;
-o-transition: 0.3s;
transition: 0.3s;
}
a:hover {
text-decoration: none;
color: #242B58;
}
table {
width: 100%;
}
p, li, span {
color: #242B58;
margin-bottom: 0;
}
/* reset css end */
/* global css start */
/* global css end */
.height-50 {
height: 40px;
display: block;
}
.pt-232 {
padding-top: 232px;
}
.section-heading {
position: relative;
}
.section-heading h2 {
font-size: 42px;
line-height: 51px;
display: inline-block;
position: relative;
padding-right: 15px;
color: rgb(255 115 0 / 25%);
text-transform: uppercase;
}
@media (max-width: 767px) {
.section-heading h2 {
font-size: 36px;
line-height: 45px;
}
}
@media only screen and (min-width: 576px) and (max-width: 767px) {
.section-heading h2 {
font-size: 42px;
line-height: 51px;
}
}
.section-heading h2::after {
width: 160px;
height: 100px;
right: 0px;
content: "";
position: absolute;
bottom: 0px;
background: #b8dee094;
z-index: -1;
}
/*--
- Margin & Padding
-----------------------------------------*/
/*-- Margin Top --*/
/*-- Margin Top --*/
.mt-175 {
margin-top: 175px;
}
/*-- Margin Bottom --*/
/*-- Margin Left --*/
/*-- Margin Right --*/
/*-- Padding Top --*/
/*-- Padding Bottom --*/
/*-- Padding Left --*/
/*-- Padding Right --*/
/* typography css start */
h1, h2, h3, h4, h5, h6 {
font-weight: 700;
color: #242B58;
margin: 0;
line-height: 1.4;
font-family: "Microsoft YaHei", "微软雅黑", "Josefin Sans", sans-serif;
}
h2 {
font-size: 32px;
}
h3 {
font-size: 22px;
}
h4 {
font-size: 20px;
}
h5 {
font-size: 18px;
}
h6 {
font-size: 16px;
}
/* typography css end */
/*--
- Overlay
------------------------------------------*/
/*-- Overlay Color --*/
/*-- Overlay Opacity --*/
/* Heder css start*/
.site-header {
margin-top: 15px;
padding: 25px 0px;
position: absolute;
width: 100%;
z-index: 2;
}
/* Navigation css */
/* form css start */
label {
font-size: fsize("14px");
}
input:not([type=radio]),
textarea {
padding: 10px 20px;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
background-color: transparent;
font-size: fsize("14px") !important;
}
input:not([type=radio])::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
color: #c9c9c9 !important;
opacity: 1;
}
input:not([type=radio])::-moz-placeholder,
textarea::-moz-placeholder {
color: #c9c9c9 !important;
opacity: 1;
}
input:not([type=radio]):-ms-input-placeholder,
textarea:-ms-input-placeholder {
color: #c9c9c9 !important;
opacity: 1;
}
input:not([type=radio]):-moz-placeholder,
textarea:-moz-placeholder {
color: #c9c9c9 !important;
opacity: 1;
}
select {
padding: 8px 10px;
cursor: pointer;
color: #242B58;
background-color: transparent;
border-radius: 0;
-webkit-border-radius: 0;
-moz-border-radius: 0;
-ms-border-radius: 0;
-o-border-radius: 0;
}
textarea {
min-height: 100px;
width: 100%;
}
input[type=radio],
input[type=range],
input[type=checkbox] {
height: auto !important;
padding: 0;
}
/* form css end */
/* hero area css*/
.hero-content {
position: relative;
margin-top: 30px;
margin-bottom: 25px;
}
.hero-content h4 {
position: relative;
font-size: 24px;
font-weight: 600;
color: #12152f;
padding-left: 65px;
line-height: 29px;
}
@media (max-width: 1199px) {
.hero-content h4 {
font-size: 18px;
line-height: 23px;
}
}
@media (max-width: 767px) {
.hero-content h4 {
font-size: 16px;
line-height: 21px;
}
}
.hero-content h4::after {
width: 50px;
height: 2px;
background: #5beeb1;
left: 0px;
top: 50%;
-webkit-transition: translateY(-50%);
-o-transition: translateY(-50%);
transition: translateY(-50%);
content: "";
position: absolute;
}
.hero-content h1 {
margin-top: 20px;
font-size: 82px;
line-height: 99px;
font-weight: 700;
color: #ffffff;
margin-bottom: 30px;
position: relative;
z-index: 2;
}
@media (max-width: 1650px) {
.hero-content h1 {
font-size: 70px;
line-height: 87px;
}
}
@media (max-width: 1199px) {
.hero-content h1 {
font-size: 45px;
line-height: 62px;
}
}
@media (max-width: 767px) {
.hero-content h1 {
font-size: 30px;
line-height: 47px;
}
}
@media only screen and (min-width: 576px) and (max-width: 767px) {
.hero-content h1 {
font-size: 45px;
line-height: 62px;
}
}
.hero-content h1 span {
font-weight: 300;
display: block;
color: #ffffff;
}
.hero-content p {
color: #B0B0B2;
line-height: 24px;
}
/* About css */
.about-area {
position: relative;
padding-top: 40px;
}
.about-content h6 {
color: #12152f;
font-size: 14px;
font-weight: 400;
line-height: 24px;
margin-bottom: 10px;
}
.about-content h2 {
color: #12152f;
font-size: 28px;
}
.about-content p {
color: #12152f;
line-height: 24px;
}
/* skill cass */
/* service css*/
/* work css */
/* testimonial css */
/* brand css */
/* blog css */
/* contact css */
/* breadcrumb css */
/* cta css */
/* contact page css */
/* blog page css */
/* single blog page css */
/* comment css */
/*Footer css*/
.site-footer {
border-top: 1px solid #00ff8c;
padding: 30px 0px;
}
@media (max-width: 767px) {
.copyright-text {
text-align: center;
margin-top: 20px;
}
}
.copyright-text p {
color: #17b874;
}

File diff suppressed because one or more lines are too long

View file

@ -1 +0,0 @@
.fa{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:inline-block;font-style:normal;font-variant:normal;text-rendering:auto;line-height:1}@keyframes fa-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@font-face{font-family:"Font Awesome 5 Brands";font-style:normal;font-weight:normal;font-display:auto;src:url(../fonts/fa-brands-400.eot);src:url(../fonts/fa-brands-400.eot) format("embedded-opentype"),url(../fonts/fa-brands-400.woff2) format("woff2"),url(../fonts/fa-brands-400.woff) format("woff"),url(../fonts/fa-brands-400.ttf) format("truetype"),url(../fonts/fa-brands-400.svg#fontawesome) format("svg")}@font-face{font-family:"Font Awesome 5 Pro";font-style:normal;font-weight:300;font-display:auto;src:url(../fonts/fa-light-300.eot);src:url(../fonts/fa-light-300.eot) format("embedded-opentype"),url(../fonts/fa-light-300.woff2) format("woff2"),url(../fonts/fa-light-300.woff) format("woff"),url(../fonts/fa-light-300.ttf) format("truetype"),url(../fonts/fa-light-300.svg#fontawesome) format("svg")}@font-face{font-family:"Font Awesome 5 Pro";font-style:normal;font-weight:400;font-display:auto;src:url(../fonts/fa-regular-400.eot);src:url(../fonts/fa-regular-400.eot) format("embedded-opentype"),url(../fonts/fa-regular-400.woff2) format("woff2"),url(../fonts/fa-regular-400.woff) format("woff"),url(../fonts/fa-regular-400.ttf) format("truetype"),url(../fonts/fa-regular-400.svg#fontawesome) format("svg")}@font-face{font-family:"Font Awesome 5 Pro";font-style:normal;font-weight:900;font-display:auto;src:url(../fonts/fa-solid-900.eot);src:url(../fonts/fa-solid-900.eot) format("embedded-opentype"),url(../fonts/fa-solid-900.woff2) format("woff2"),url(../fonts/fa-solid-900.woff) format("woff"),url(../fonts/fa-solid-900.ttf) format("truetype"),url(../fonts/fa-solid-900.svg#fontawesome) format("svg")}.fa{font-family:"Font Awesome 5 Pro";font-weight:900}

View file

@ -1,108 +0,0 @@
/*!
Theme: Default
Description: Original highlight.js style
Author: (c) Ivan Sagalaev <maniac@softwaremaniacs.org>
Maintainer: @highlightjs/core-team
Website: https://highlightjs.org/
License: see project LICENSE
Touched: 2021
*/
pre {
white-space: pre-wrap; /* 允许换行 */
word-wrap: break-word; /* 允许在单词内换行 */
max-width: 100%; /* 最大宽度为父容器的宽度 */
overflow: auto; /* 添加滚动条 */
}
pre code.hljs {
display: block;
overflow-x: auto;
padding: 1em
}
code.hljs {
padding: 3px 5px
}
.hljs {
background: #f3f3f3;
color: #444
}
.hljs-comment {
color: #697070
}
.hljs-punctuation,
.hljs-tag {
color: #444a
}
.hljs-tag .hljs-attr,
.hljs-tag .hljs-name {
color: #444
}
.hljs-attribute,
.hljs-doctag,
.hljs-keyword,
.hljs-meta .hljs-keyword,
.hljs-name,
.hljs-selector-tag {
font-weight: 700
}
.hljs-deletion,
.hljs-number,
.hljs-quote,
.hljs-selector-class,
.hljs-selector-id,
.hljs-string,
.hljs-template-tag,
.hljs-type {
color: #800
}
.hljs-section,
.hljs-title {
color: #800;
font-weight: 700
}
.hljs-link,
.hljs-operator,
.hljs-regexp,
.hljs-selector-attr,
.hljs-selector-pseudo,
.hljs-symbol,
.hljs-template-variable,
.hljs-variable {
color: #ab5656
}
.hljs-literal {
color: #695
}
.hljs-addition,
.hljs-built_in,
.hljs-bullet,
.hljs-code {
color: #397300
}
.hljs-meta {
color: #1f7199
}
.hljs-meta .hljs-string {
color: #38a
}
.hljs-emphasis {
font-style: italic
}
.hljs-strong {
font-weight: 700
}

Some files were not shown because too many files have changed in this diff Show more