Compare commits
170 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7c97026b7 | ||
|
|
0ff7825387 | ||
|
|
c2b25a84c7 | ||
|
|
553e239db3 | ||
|
|
e3a3e4dc29 | ||
|
|
4e4e41b0d6 | ||
|
|
5594b0baa9 | ||
|
|
e2ad3fe248 | ||
|
|
9bd88eac84 | ||
|
|
431de382dc | ||
|
|
b241240fc6 | ||
|
|
40fa028408 | ||
|
|
15f3aac88e | ||
|
|
90f0c3a80b | ||
|
|
d2a852d5eb | ||
|
|
85543deca3 | ||
|
|
142759ac50 | ||
|
|
da20aed4b0 | ||
|
|
c0f4af05e3 | ||
|
|
468bed7705 | ||
|
|
0878af0239 | ||
|
|
aa0487edc4 | ||
|
|
76cef650b4 | ||
|
|
78bcf7f4ce | ||
|
|
c0a9fd5208 | ||
|
|
07123b70ad | ||
|
|
b579d24d19 | ||
|
|
e2eeee455a | ||
|
|
32ad20416c | ||
|
|
799af86739 | ||
|
|
c3f431118b | ||
|
|
a3944f86b7 | ||
|
|
365a7df1ff | ||
|
|
639152f987 | ||
|
|
fb8ad3790d | ||
|
|
902321026b | ||
|
|
9b0d7dbee8 | ||
|
|
634c879108 | ||
|
|
57a1d6e3cd | ||
|
|
9081b22ce9 | ||
|
|
73e12b1fdd | ||
|
|
5fca2e9fa3 | ||
|
|
917feec5d8 | ||
|
|
c52195cef8 | ||
|
|
630e88b8c4 | ||
|
|
734eb7a3fb | ||
|
|
e55fc06686 | ||
|
|
5fee11323b | ||
|
|
814c3a2565 | ||
|
|
d2a22a3ee5 | ||
|
|
92278932ef | ||
|
|
9c6a3d6110 | ||
|
|
e30217542d | ||
|
|
1edf591721 | ||
|
|
60fd2ae0e0 | ||
|
|
3e509f6663 | ||
|
|
bf48eae9fe | ||
|
|
31a84325d4 | ||
|
|
b1d0056429 | ||
|
|
6ecc61ac5d | ||
|
|
e02ab1fbad | ||
|
|
47dc009505 | ||
|
|
f1584b60e8 | ||
|
|
d1c15f58c4 | ||
|
|
d422a805f6 | ||
|
|
08b5772420 | ||
|
|
8fad91ade7 | ||
|
|
560378fd45 | ||
|
|
95ce026813 | ||
|
|
71c5a88c01 | ||
|
|
a8e9a24ca7 | ||
|
|
95724845cf | ||
|
|
c5552893d7 | ||
|
|
e46d3685a0 | ||
|
|
116ed7b0bf | ||
|
|
2ad7567548 | ||
|
|
b3cfe7a976 | ||
|
|
0b13846861 | ||
|
|
951e9d8d39 | ||
|
|
1411c45811 | ||
|
|
c797ff5cb3 | ||
|
|
25692f8371 | ||
|
|
3a1466bace | ||
|
|
cf788b190a | ||
|
|
6cd16826fd | ||
|
|
b288cd612e | ||
|
|
efc9e81e83 | ||
|
|
db502e1412 | ||
|
|
41ddc6a8e1 | ||
|
|
0481726608 | ||
|
|
73bf8c01a9 | ||
|
|
8a0cb90ccc | ||
|
|
f4be5b985a | ||
|
|
0a9f9b618b | ||
|
|
af76b89fd4 | ||
|
|
de6632d631 | ||
|
|
7bebee202e | ||
|
|
bc5e835f78 | ||
|
|
a4cfd0c380 | ||
|
|
86d720ecee | ||
|
|
379bbcdd14 | ||
|
|
84a19aafc2 | ||
|
|
cf03b65a4d | ||
|
|
461d70a696 | ||
|
|
6b8ba6302a | ||
|
|
c0a1b5606e | ||
|
|
00ade41a76 | ||
|
|
514ab7e9e4 | ||
|
|
24c203f8d4 | ||
|
|
cbcbdda4c0 | ||
|
|
a2fcd31f24 | ||
|
|
07b92d4ede | ||
|
|
ed4ff67760 | ||
|
|
9c4644c969 | ||
|
|
dd91c2a4e0 | ||
|
|
7e8e15a628 | ||
|
|
076c56d1d9 | ||
|
|
133a24e25f | ||
|
|
73a67b8f64 | ||
|
|
222b3eaa4c | ||
|
|
c4baccdc48 | ||
|
|
7021a08ecf | ||
|
|
e88b9bef13 | ||
|
|
c17cc16c0e | ||
|
|
d7d037618f | ||
|
|
01edad7717 | ||
|
|
eff787a2b7 | ||
|
|
8616526136 | ||
|
|
32e3963390 | ||
|
|
7d52e6dd1e | ||
|
|
ba41015df8 | ||
|
|
f084460d1c | ||
|
|
a4ef23d603 | ||
|
|
d3daa654a7 | ||
|
|
9576edf26f | ||
|
|
5b74ac9cc6 | ||
|
|
444e2ec2e8 | ||
|
|
60b7874f65 | ||
|
|
07cac12dac | ||
|
|
4f3bfd1d4a | ||
|
|
451a456f58 | ||
|
|
5fe1e20e4a | ||
|
|
54381ed2e2 | ||
|
|
ffd4da91cf | ||
|
|
a2ffa3cb3a | ||
|
|
ecc2afd164 | ||
|
|
45cbfbf002 | ||
|
|
a689406b28 | ||
|
|
2ff82b1249 | ||
|
|
8e1b4edc91 | ||
|
|
dea74e242e | ||
|
|
162f561523 | ||
|
|
50e672e79b | ||
|
|
c8fa086565 | ||
|
|
cd91cb1afd | ||
|
|
e6db6a58f0 | ||
|
|
ab08df9823 | ||
|
|
8619ac4667 | ||
|
|
de34d97529 | ||
|
|
0cdacfdb2f | ||
|
|
976713490a | ||
|
|
002a57704f | ||
|
|
9dd3655b81 | ||
|
|
d1de182451 | ||
|
|
dee84e9307 | ||
|
|
0fdf75eba0 | ||
|
|
2293969070 | ||
|
|
f7f87e266f | ||
|
|
f95af40ab8 | ||
|
|
20d6135658 |
@@ -1,6 +1,7 @@
|
||||
**/node_modules
|
||||
*/node_modules
|
||||
node_modules
|
||||
Dockerfile
|
||||
.git
|
||||
.husky
|
||||
.github
|
||||
.vscode
|
||||
.*
|
||||
*/.*
|
||||
!.env
|
||||
|
||||
8
.env
@@ -1,4 +1,10 @@
|
||||
# Glob API URL
|
||||
VITE_GLOB_API_URL=/api
|
||||
|
||||
VITE_APP_API_BASE_URL=http://localhost:3002/
|
||||
VITE_APP_API_BASE_URL=http://127.0.0.1:3002/
|
||||
|
||||
# Whether long replies are supported, which may result in higher API fees
|
||||
VITE_GLOB_OPEN_LONG_REPLY=false
|
||||
|
||||
# When you want to use PWA
|
||||
VITE_GLOB_APP_PWA=false
|
||||
|
||||
2
.eslintignore
Normal file
@@ -0,0 +1,2 @@
|
||||
docker-compose
|
||||
kubernetes
|
||||
22
.github/workflows/issues_close.yml
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
name: Close inactive issues
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 1 * * *'
|
||||
|
||||
jobs:
|
||||
close-issues:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/stale@v5
|
||||
with:
|
||||
days-before-issue-stale: 10
|
||||
days-before-issue-close: 5
|
||||
stale-issue-label: stale
|
||||
stale-issue-message: This issue is stale because it has been open for 10 days with no activity.
|
||||
close-issue-message: This issue was closed because it has been inactive for 5 days since being marked as stale.
|
||||
days-before-pr-stale: -1
|
||||
days-before-pr-close: -1
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
3
.gitignore
vendored
@@ -27,3 +27,6 @@ coverage
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
# Environment variables files
|
||||
/service/.env
|
||||
|
||||
25
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "chrome",
|
||||
"request": "launch",
|
||||
"name": "Launch Web App",
|
||||
"url": "http://localhost:1002",
|
||||
"webRoot": "${workspaceFolder}"
|
||||
},
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Launch Service Server",
|
||||
"runtimeExecutable": "${workspaceFolder}/service/node_modules/.bin/esno",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"program": "${workspaceFolder}/service/src/index.ts",
|
||||
"outFiles": ["${workspaceFolder}/service/**/*.js"],
|
||||
"envFile": "${workspaceFolder}/service/.env"
|
||||
}
|
||||
]
|
||||
}
|
||||
7
.vscode/settings.json
vendored
@@ -29,9 +29,15 @@
|
||||
"dockerhub",
|
||||
"esno",
|
||||
"GPTAPI",
|
||||
"highlightjs",
|
||||
"hljs",
|
||||
"iconify",
|
||||
"katex",
|
||||
"katexmath",
|
||||
"linkify",
|
||||
"logprobs",
|
||||
"mdhljs",
|
||||
"mila",
|
||||
"nodata",
|
||||
"OPENAI",
|
||||
"pinia",
|
||||
@@ -39,6 +45,7 @@
|
||||
"rushstack",
|
||||
"Sider",
|
||||
"tailwindcss",
|
||||
"traptitech",
|
||||
"tsup",
|
||||
"Typecheck",
|
||||
"unplugin",
|
||||
|
||||
278
CHANGELOG.md
@@ -1,3 +1,281 @@
|
||||
## v2.10.9
|
||||
|
||||
`2023-04-03`
|
||||
|
||||
> 更新默认 `accessToken` 反代地址为 [[acheong08](https://github.com/acheong08)] 的 `https://bypass.churchless.tech/api/conversation`
|
||||
|
||||
## Enhancement
|
||||
- 添加 `socks5` 代理认证 [[yimiaoxiehou](https://github.com/Chanzhaoyu/chatgpt-web/pull/999)]
|
||||
- 添加 `socks` 代理用户名密码的配置 [[hank-cp](https://github.com/Chanzhaoyu/chatgpt-web/pull/890)]
|
||||
- 添加可选日志打印 [[zcong1993](https://github.com/Chanzhaoyu/chatgpt-web/pull/1041)]
|
||||
- 更新侧边栏按钮本地化[[simonwu53](https://github.com/Chanzhaoyu/chatgpt-web/pull/911)]
|
||||
- 优化代码块滚动条高度 [[Fog3211](https://github.com/Chanzhaoyu/chatgpt-web/pull/1153)]
|
||||
## BugFix
|
||||
- 修复 `PWA` 问题 [[bingo235](https://github.com/Chanzhaoyu/chatgpt-web/pull/807)]
|
||||
- 修复 `ESM` 错误 [[kidonng](https://github.com/Chanzhaoyu/chatgpt-web/pull/826)]
|
||||
- 修复反向代理开启时限流失效的问题 [[gitgitgogogo](https://github.com/Chanzhaoyu/chatgpt-web/pull/863)]
|
||||
- 修复 `docker` 构建时 `.env` 可能被忽略的问题 [[zaiMoe](https://github.com/Chanzhaoyu/chatgpt-web/pull/877)]
|
||||
- 修复导出异常错误 [[KingTwinkle](https://github.com/Chanzhaoyu/chatgpt-web/pull/938)]
|
||||
- 修复空值异常 [[vchenpeng](https://github.com/Chanzhaoyu/chatgpt-web/pull/1103)]
|
||||
- 移动端上的体验问题
|
||||
|
||||
## Other
|
||||
- `Docker` 容器名字名义 [[LOVECHEN](https://github.com/Chanzhaoyu/chatgpt-web/pull/1035)]
|
||||
- `kubernetes` 部署配置 [[CaoYunzhou](https://github.com/Chanzhaoyu/chatgpt-web/pull/1001)]
|
||||
- 感谢 [[assassinliujie](https://github.com/Chanzhaoyu/chatgpt-web/pull/962)] 和 [[puppywang](https://github.com/Chanzhaoyu/chatgpt-web/pull/1017)] 的某些贡献
|
||||
- 更新 `kubernetes/deploy.yaml` [[idawnwon](https://github.com/Chanzhaoyu/chatgpt-web/pull/1085)]
|
||||
- 文档更新 [[#yi-ge](https://github.com/Chanzhaoyu/chatgpt-web/pull/883)]
|
||||
- 文档更新 [[weifeng12x](https://github.com/Chanzhaoyu/chatgpt-web/pull/880)]
|
||||
- 依赖更新
|
||||
|
||||
## v2.10.8
|
||||
|
||||
`2023-03-23`
|
||||
|
||||
如遇问题,请删除 `node_modules` 重新安装依赖。
|
||||
|
||||
## Feature
|
||||
- 显示回复消息原文的选项 [[yilozt](https://github.com/Chanzhaoyu/chatgpt-web/pull/672)]
|
||||
- 添加单 `IP` 每小时请求限制。环境变量: `MAX_REQUEST_PER_HOUR` [[zhuxindong ](https://github.com/Chanzhaoyu/chatgpt-web/pull/718)]
|
||||
- 前端添加角色设定,仅 `API` 方式可见 [[quzard](https://github.com/Chanzhaoyu/chatgpt-web/pull/768)]
|
||||
- `OPENAI_API_MODEL` 变量现在对 `ChatGPTUnofficialProxyAPI` 也生效,注意:`Token` 和 `API` 的模型命名不一致,不能直接填入 `gpt-3.5` 或者 `gpt-4` [[hncboy](https://github.com/Chanzhaoyu/chatgpt-web/pull/632)]
|
||||
- 添加繁体中文 `Prompts` [[PeterDaveHello](https://github.com/Chanzhaoyu/chatgpt-web/pull/796)]
|
||||
|
||||
## Enhancement
|
||||
- 重置回答时滚动定位至该回答 [[shunyue1320](https://github.com/Chanzhaoyu/chatgpt-web/pull/781)]
|
||||
- 当 `API` 是 `gpt-4` 时增加可用的 `Max Tokens` [[simonwu53](https://github.com/Chanzhaoyu/chatgpt-web/pull/729)]
|
||||
- 判断和忽略回复字符 [[liut](https://github.com/Chanzhaoyu/chatgpt-web/pull/474)]
|
||||
- 切换会话时,自动聚焦输入框 [[JS-an](https://github.com/Chanzhaoyu/chatgpt-web/pull/735)]
|
||||
- 渲染的链接新窗口打开
|
||||
- 查询余额可选 `API_BASE_URL` 代理地址
|
||||
- `config` 接口添加验证防止被无限制调用
|
||||
- `PWA` 默认不开启,现在需手动修改 `.env` 文件 `VITE_GLOB_APP_PWA` 变量
|
||||
- 当网络连接时,刷新页面,`500` 错误页自动跳转到主页
|
||||
|
||||
## BugFix
|
||||
- `scrollToBottom` 调回 `scrollToBottomIfAtBottom` [[shunyue1320](https://github.com/Chanzhaoyu/chatgpt-web/pull/771)]
|
||||
- 重置异常的 `loading` 会话
|
||||
|
||||
## Common
|
||||
- 创建 `start.cmd` 在 `windows` 下也可以运行 [vulgatecnn](https://github.com/Chanzhaoyu/chatgpt-web/pull/656)]
|
||||
- 添加 `visual-studio-code` 中调试配置 [[ChandlerVer5](https://github.com/Chanzhaoyu/chatgpt-web/pull/296)]
|
||||
- 修复文档中 `docker` 端口为本地 [[kilvn](https://github.com/Chanzhaoyu/chatgpt-web/pull/802)]
|
||||
## Other
|
||||
- 依赖更新
|
||||
|
||||
|
||||
## v2.10.7
|
||||
|
||||
`2023-03-17`
|
||||
|
||||
## BugFix
|
||||
- 回退 `chatgpt` 版本,原因:导致 `OPENAI_API_BASE_URL` 代理失效
|
||||
- 修复缺省状态的 `usingContext` 默认值
|
||||
|
||||
## v2.10.6
|
||||
|
||||
`2023-03-17`
|
||||
|
||||
## Feature
|
||||
- 显示 `API` 余额 [[pzcn](https://github.com/Chanzhaoyu/chatgpt-web/pull/582)]
|
||||
|
||||
## Enhancement
|
||||
- 美化滚动条样式和 `UI` 保持一致 [[haydenull](https://github.com/Chanzhaoyu/chatgpt-web/pull/617)]
|
||||
- 优化移动端 `Prompt` 样式 [[CornerSkyless](https://github.com/Chanzhaoyu/chatgpt-web/pull/608)]
|
||||
- 上下文开关改为全局开关,现在记录在本地缓存中
|
||||
- 配置信息按接口类型显示
|
||||
|
||||
## Perf
|
||||
- 优化函数方法 [[kirklin](https://github.com/Chanzhaoyu/chatgpt-web/pull/583)]
|
||||
- 字符错误 [[pdsuwwz](https://github.com/Chanzhaoyu/chatgpt-web/pull/585)]
|
||||
- 文档描述错误 [[lizhongyuan3](https://github.com/Chanzhaoyu/chatgpt-web/pull/636)]
|
||||
|
||||
## BugFix
|
||||
- 修复 `Prompt` 导入、导出兼容性错误
|
||||
- 修复 `highlight.js` 控制台兼容性警告
|
||||
|
||||
## Other
|
||||
- 依赖更新
|
||||
|
||||
## v2.10.5
|
||||
|
||||
`2023-03-13`
|
||||
|
||||
更新依赖,`access_token` 默认代理为 [acheong08](https://github.com/acheong08) 的 `https://bypass.duti.tech/api/conversation`
|
||||
|
||||
## Feature
|
||||
- `Prompt` 商店在线导入可以导入两种 `recommend.json`里提到的模板 [simonwu53](https://github.com/Chanzhaoyu/chatgpt-web/pull/521)
|
||||
- 支持 `HTTPS_PROXY` [whatwewant](https://github.com/Chanzhaoyu/chatgpt-web/pull/308)
|
||||
- `Prompt` 添加查询筛选
|
||||
|
||||
## Enhancement
|
||||
- 调整输入框最大行数 [yi-ge](https://github.com/Chanzhaoyu/chatgpt-web/pull/502)
|
||||
- 优化 `docker` 打包 [whatwewant](https://github.com/Chanzhaoyu/chatgpt-web/pull/520)
|
||||
- `Prompt` 添加翻译和优化布局
|
||||
- 「繁体中文」补全和审阅 [PeterDaveHello](https://github.com/Chanzhaoyu/chatgpt-web/pull/542)
|
||||
- 语言选择调整为下路框形式
|
||||
- 权限输入框类型调整为密码形式
|
||||
|
||||
## BugFix
|
||||
- `JSON` 导入检查 [Nothing1024](https://github.com/Chanzhaoyu/chatgpt-web/pull/523)
|
||||
- 修复 `AUTH_SECRET_KEY` 模式下跨域异常并添加对 `node.js 19` 版本的支持 [yi-ge](https://github.com/Chanzhaoyu/chatgpt-web/pull/499)
|
||||
- 确定清空上下文时不应该重置会话标题
|
||||
|
||||
## Other
|
||||
- 调整文档
|
||||
- 更新依赖
|
||||
|
||||
## v2.10.4
|
||||
|
||||
`2023-03-11`
|
||||
|
||||
## Feature
|
||||
- 感谢 [Nothing1024](https://github.com/Chanzhaoyu/chatgpt-web/pull/268) 添加 `Prompt` 模板和 `Prompt` 商店支持
|
||||
|
||||
## Enhancement
|
||||
- 设置添加关闭按钮[#495]
|
||||
|
||||
## Demo
|
||||
|
||||

|
||||
|
||||
## v2.10.3
|
||||
|
||||
`2023-03-10`
|
||||
|
||||
> 声明:除 `ChatGPTUnofficialProxyAPI` 使用的非官方代理外,本项目代码包括上游引用包均开源在 `GitHub`,如果你觉得本项目有监控后门或有问题导致你的账号、API被封,那我很抱歉。我可能`BUG`写的多,但我不缺德。此次主要为前端界面调整,周末愉快。
|
||||
|
||||
## Feature
|
||||
- 支持长回复 [[yi-ge](https://github.com/Chanzhaoyu/chatgpt-web/pull/450)][[详情](https://github.com/Chanzhaoyu/chatgpt-web/pull/450)]
|
||||
- 支持 `PWA` [[chenxch](https://github.com/Chanzhaoyu/chatgpt-web/pull/452)]
|
||||
|
||||
## Enhancement
|
||||
- 调整移动端按钮和优化布局
|
||||
- 调整 `iOS` 上安全距离
|
||||
- 简化 `docker-compose` 部署 [[cloudGrin](https://github.com/Chanzhaoyu/chatgpt-web/pull/466)]
|
||||
|
||||
## BugFix
|
||||
- 修复清空会话侧边栏标题不会重置的问题 [[RyanXinOne](https://github.com/Chanzhaoyu/chatgpt-web/pull/453)]
|
||||
- 修复设置文字过长时导致的设置按钮消失的问题
|
||||
|
||||
## Other
|
||||
- 更新依赖
|
||||
|
||||
## v2.10.2
|
||||
|
||||
`2023-03-09`
|
||||
|
||||
衔接 `2.10.1` 版本[详情](https://github.com/Chanzhaoyu/chatgpt-web/releases/tag/v2.10.1)
|
||||
|
||||
## Enhancement
|
||||
- 移动端下输入框获得焦点时左侧按钮隐藏
|
||||
|
||||
## BugFix
|
||||
- 修复 `2.10.1` 中添加 `OPENAI_API_MODEL` 变量的判断错误,会导致默认模型指定失效,抱歉
|
||||
- 回退 `2.10.1` 中前端变量影响 `Docker` 打包
|
||||
|
||||
## v2.10.1
|
||||
|
||||
`2023-03-09`
|
||||
|
||||
注意:删除了 `.env` 文件改用 `.env.example` 代替,如果是手动部署的同学现在需要手动创建 `.env` 文件并从 `.env.example` 中复制需要的变量,并且 `.env` 文件现在会在 `Git` 提交中被忽略,原因如下:
|
||||
|
||||
- 在项目中添加 `.env` 从一开始就是个错误的示范
|
||||
- 如果是 `Fork` 项目进行修改测试总是会被 `Git` 修改提示给打扰
|
||||
- 感谢 [yi-ge](https://github.com/Chanzhaoyu/chatgpt-web/pull/395) 的提醒和修改
|
||||
|
||||
|
||||
这两天开始,官方已经开始对第三方代理进行了拉闸, `accessToken` 即将或已经开始可能会不可使用。异常 `API` 使用也开始封号,封号缘由不明,如果出现使用 `API` 提示错误,请查看后端控制台信息,或留意邮箱。
|
||||
|
||||
## Feature
|
||||
- 感谢 [CornerSkyless](https://github.com/Chanzhaoyu/chatgpt-web/pull/393) 添加是否发送上下文开关功能
|
||||
|
||||
## Enhancement
|
||||
- 感谢 [nagaame](https://github.com/Chanzhaoyu/chatgpt-web/pull/415) 优化`docker`打包镜像文件过大的问题
|
||||
- 感谢 [xieccc](https://github.com/Chanzhaoyu/chatgpt-web/pull/404) 新增 `API` 模型配置变量 `OPENAI_API_MODEL`
|
||||
- 感谢 [acongee](https://github.com/Chanzhaoyu/chatgpt-web/pull/394) 优化输出时滚动条问题
|
||||
|
||||
## BugFix
|
||||
- 感谢 [CornerSkyless](https://github.com/Chanzhaoyu/chatgpt-web/pull/392) 修复导出图片会丢失头像的问题
|
||||
- 修复深色模式导出图片的样式问题
|
||||
|
||||
|
||||
## v2.10.0
|
||||
|
||||
`2023-03-07`
|
||||
|
||||
- 老规矩,手动部署的同学需要删除 `node_modules` 安装包重新安装降低出错概率,其他部署不受影响,但是可能会有缓存问题。
|
||||
- 虽然说了更新放缓,但是 `issues` 不看, `PR` 不改我睡不着,我的邮箱从每天早上`8`点到凌晨`12`永远在滴滴滴,所以求求各位,超时的`issues`自己关闭下哈,我真的需要缓冲一下。
|
||||
- 演示图片请看最后
|
||||
|
||||
## Feature
|
||||
- 添加权限功能,用法:`service/.env` 中的 `AUTH_SECRET_KEY` 变量添加密码
|
||||
- 感谢 [PeterDaveHello](https://github.com/Chanzhaoyu/chatgpt-web/pull/348) 添加「繁体中文」翻译
|
||||
- 感谢 [GermMC](https://github.com/Chanzhaoyu/chatgpt-web/pull/369) 添加聊天记录导入、导出、清空的功能
|
||||
- 感谢 [CornerSkyless](https://github.com/Chanzhaoyu/chatgpt-web/pull/374) 添加会话保存为本地图片的功能
|
||||
|
||||
|
||||
## Enhancement
|
||||
- 感谢 [CornerSkyless](https://github.com/Chanzhaoyu/chatgpt-web/pull/363) 添加 `ctrl+enter` 发送消息
|
||||
- 现在新消息只有在结束了之后才滚动到底部,而不是之前的强制性
|
||||
- 优化部分代码
|
||||
|
||||
## BugFix
|
||||
- 转义状态码前端显示,防止直接暴露 `key`(我可能需要更多的状态码补充)
|
||||
|
||||
## Other
|
||||
- 更新依赖到最新
|
||||
|
||||
## 演示
|
||||
> 不是界面最新效果,有美化改动
|
||||
|
||||
权限
|
||||
|
||||

|
||||
|
||||
聊天记录导出
|
||||
|
||||

|
||||
|
||||
保存图片到本地
|
||||
|
||||

|
||||
|
||||
## v2.9.3
|
||||
|
||||
`2023-03-06`
|
||||
|
||||
## Enhancement
|
||||
- 感谢 [ChandlerVer5](https://github.com/Chanzhaoyu/chatgpt-web/pull/305) 使用 `markdown-it` 替换 `marked`,解决代码块闪烁的问题
|
||||
- 感谢 [shansing](https://github.com/Chanzhaoyu/chatgpt-web/pull/277) 改善文档
|
||||
- 感谢 [nalf3in](https://github.com/Chanzhaoyu/chatgpt-web/pull/293) 添加英文翻译
|
||||
|
||||
## BugFix
|
||||
- 感谢[sepcnt ](https://github.com/Chanzhaoyu/chatgpt-web/pull/279) 修复切换记录时编辑状态未关闭的问题
|
||||
- 修复复制代码的兼容性报错问题
|
||||
- 修复部分优化小问题
|
||||
|
||||
## v2.9.2
|
||||
|
||||
`2023-03-04`
|
||||
|
||||
手动部署的同学,务必删除根目录和`service`中的`node_modules`重新安装依赖,降低出现问题的概率,自动部署的不需要做改动。
|
||||
|
||||
### Feature
|
||||
- 感谢 [hyln9](https://github.com/Chanzhaoyu/chatgpt-web/pull/247) 添加对渲染 `LaTex` 数学公式的支持
|
||||
- 感谢 [ottocsb](https://github.com/Chanzhaoyu/chatgpt-web/pull/227) 添加支持 `webAPP` (苹果添加到主页书签访问)支持
|
||||
- 添加 `OPENAI_API_BASE_URL` 可选环境变量[#249]
|
||||
## Enhancement
|
||||
- 优化在高分屏上主题内容的最大宽度[#257]
|
||||
- 现在文字按单词截断[#215][#225]
|
||||
### BugFix
|
||||
- 修复动态生成时代码块不能被复制的问题[#251][#260]
|
||||
- 修复 `iOS` 移动端输入框不会被键盘顶起的问题[#256]
|
||||
- 修复控制台渲染警告
|
||||
## Other
|
||||
- 更新依赖至最新
|
||||
- 修改 `README` 内容
|
||||
|
||||
## v2.9.1
|
||||
|
||||
`2023-03-02`
|
||||
|
||||
49
CONTRIBUTING.en.md
Normal file
@@ -0,0 +1,49 @@
|
||||
# Contribution Guide
|
||||
Thank you for your valuable time. Your contributions will make this project better! Before submitting a contribution, please take some time to read the getting started guide below.
|
||||
|
||||
## Semantic Versioning
|
||||
This project follows semantic versioning. We release patch versions for important bug fixes, minor versions for new features or non-important changes, and major versions for significant and incompatible changes.
|
||||
|
||||
Each major change will be recorded in the `changelog`.
|
||||
|
||||
## Submitting Pull Request
|
||||
1. Fork [this repository](https://github.com/Chanzhaoyu/chatgpt-web) and create a branch from `main`. For new feature implementations, submit a pull request to the `feature` branch. For other changes, submit to the `main` branch.
|
||||
2. Install the `pnpm` tool using `npm install pnpm -g`.
|
||||
3. Install the `Eslint` plugin for `VSCode`, or enable `eslint` functionality for other editors such as `WebStorm`.
|
||||
4. Execute `pnpm bootstrap` in the root directory.
|
||||
5. Execute `pnpm install` in the `/service/` directory.
|
||||
6. Make changes to the codebase. If applicable, ensure that appropriate testing has been done.
|
||||
7. Execute `pnpm lint:fix` in the root directory to perform a code formatting check.
|
||||
8. Execute `pnpm type-check` in the root directory to perform a type check.
|
||||
9. Submit a git commit, following the [Commit Guidelines](#commit-guidelines).
|
||||
10. Submit a `pull request`. If there is a corresponding `issue`, please link it using the [linking-a-pull-request-to-an-issue keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword).
|
||||
|
||||
## Commit Guidelines
|
||||
|
||||
Commit messages should follow the [conventional-changelog standard](https://www.conventionalcommits.org/en/v1.0.0/):
|
||||
|
||||
```bash
|
||||
<type>[optional scope]: <description>
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer]
|
||||
```
|
||||
|
||||
### Commit Types
|
||||
|
||||
The following is a list of commit types:
|
||||
|
||||
- feat: New feature or functionality
|
||||
- fix: Bug fix
|
||||
- docs: Documentation update
|
||||
- style: Code style or component style update
|
||||
- refactor: Code refactoring, no new features or bug fixes introduced
|
||||
- perf: Performance optimization
|
||||
- test: Unit test
|
||||
- chore: Other commits that do not modify src or test files
|
||||
|
||||
|
||||
## License
|
||||
|
||||
[MIT](./license)
|
||||
50
Dockerfile
@@ -1,20 +1,56 @@
|
||||
# build front-end
|
||||
FROM node:lts-alpine AS builder
|
||||
FROM node:lts-alpine AS frontend
|
||||
|
||||
RUN npm install pnpm -g
|
||||
|
||||
COPY ./ /app
|
||||
WORKDIR /app
|
||||
|
||||
RUN npm install pnpm -g && pnpm install && pnpm run build
|
||||
COPY ./package.json /app
|
||||
|
||||
COPY ./pnpm-lock.yaml /app
|
||||
|
||||
RUN pnpm install
|
||||
|
||||
COPY . /app
|
||||
|
||||
RUN pnpm run build
|
||||
|
||||
# build backend
|
||||
FROM node:lts-alpine as backend
|
||||
|
||||
RUN npm install pnpm -g
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY /service/package.json /app
|
||||
|
||||
COPY /service/pnpm-lock.yaml /app
|
||||
|
||||
RUN pnpm install
|
||||
|
||||
COPY /service /app
|
||||
|
||||
RUN pnpm build
|
||||
|
||||
# service
|
||||
FROM node:lts-alpine
|
||||
|
||||
COPY /service /app
|
||||
COPY --from=builder /app/dist /app/public
|
||||
RUN npm install pnpm -g
|
||||
|
||||
WORKDIR /app
|
||||
RUN npm install pnpm -g && pnpm install
|
||||
|
||||
COPY /service/package.json /app
|
||||
|
||||
COPY /service/pnpm-lock.yaml /app
|
||||
|
||||
RUN pnpm install --production && rm -rf /root/.npm /root/.pnpm-store /usr/local/share/.cache /tmp/*
|
||||
|
||||
COPY /service /app
|
||||
|
||||
COPY --from=frontend /app/dist /app/public
|
||||
|
||||
COPY --from=backend /app/build /app/build
|
||||
|
||||
EXPOSE 3002
|
||||
|
||||
CMD ["pnpm", "run", "start"]
|
||||
CMD ["pnpm", "run", "prod"]
|
||||
|
||||
130
README.md
@@ -2,8 +2,8 @@
|
||||
|
||||
> 声明:此项目只发布于 Github,基于 MIT 协议,免费且作为开源学习使用。并且不会有任何形式的卖号、付费服务、讨论群、讨论组等行为。谨防受骗。
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
- [ChatGPT Web](#chatgpt-web)
|
||||
- [介绍](#介绍)
|
||||
@@ -18,6 +18,7 @@
|
||||
- [测试环境运行](#测试环境运行)
|
||||
- [后端服务](#后端服务)
|
||||
- [前端网页](#前端网页)
|
||||
- [环境变量](#环境变量)
|
||||
- [打包](#打包)
|
||||
- [使用 Docker](#使用-docker)
|
||||
- [Docker 参数示例](#docker-参数示例)
|
||||
@@ -36,30 +37,34 @@
|
||||
|
||||
支持双模型,提供了两种非官方 `ChatGPT API` 方法
|
||||
|
||||
| 方式 | 免费? | 可靠性 | 质量 |
|
||||
| ---- | ---- | ---- | ---- |
|
||||
| `ChatGPTAPI(GPT-3)` | 否 | 可靠 | 较笨 |
|
||||
| `ChatGPTUnofficialProxyAPI(网页 accessToken)` | 是 | 相对不可靠 | 聪明 |
|
||||
| 方式 | 免费? | 可靠性 | 质量 |
|
||||
| --------------------------------------------- | ------ | ---------- | ---- |
|
||||
| `ChatGPTAPI(gpt-3.5-turbo-0301)` | 否 | 可靠 | 相对较笨 |
|
||||
| `ChatGPTUnofficialProxyAPI(网页 accessToken)` | 是 | 相对不可靠 | 聪明 |
|
||||
|
||||
对比:
|
||||
1. `ChatGPTAPI` 使用 `text-davinci-003` 通过官方`OpenAI`补全`API`模拟`ChatGPT`(最稳健的方法,但它不是免费的,并且没有使用针对聊天进行微调的模型)
|
||||
2. `ChatGPTUnofficialProxyAPI` 使用非官方代理服务器访问 `ChatGPT` 的后端`API`,绕过`Cloudflare`(使用真实的的`ChatGPT`,非常轻量级,但依赖于第三方服务器,并且有速率限制)
|
||||
1. `ChatGPTAPI` 使用 `gpt-3.5-turbo` 通过 `OpenAI` 官方 `API` 调用 `ChatGPT`
|
||||
2. `ChatGPTUnofficialProxyAPI` 使用非官方代理服务器访问 `ChatGPT` 的后端`API`,绕过`Cloudflare`(依赖于第三方服务器,并且有速率限制)
|
||||
|
||||
[查看详情](https://github.com/Chanzhaoyu/chatgpt-web/issues/138)
|
||||
警告:
|
||||
1. 你应该首先使用 `API` 方式
|
||||
2. 使用 `API` 时,如果网络不通,那是国内被墙了,你需要自建代理,绝对不要使用别人的公开代理,那是危险的。
|
||||
3. 使用 `accessToken` 方式时反向代理将向第三方暴露您的访问令牌,这样做应该不会产生任何不良影响,但在使用这种方法之前请考虑风险。
|
||||
4. 使用 `accessToken` 时,不管你是国内还是国外的机器,都会使用代理。默认代理为 [acheong08](https://github.com/acheong08) 大佬的 `https://bypass.churchless.tech/api/conversation`,这不是后门也不是监听,除非你有能力自己翻过 `CF` 验证,用前请知悉。[社区代理](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy)(注意:只有这两个是推荐,其他第三方来源,请自行甄别)
|
||||
5. 把项目发布到公共网络时,你应该设置 `AUTH_SECRET_KEY` 变量添加你的密码访问权限,你也应该修改 `index.html` 中的 `title`,防止被关键词搜索到。
|
||||
|
||||
切换方式:
|
||||
1. 进入 `service/.env` 文件
|
||||
1. 进入 `service/.env.example` 文件,复制内容到 `service/.env` 文件
|
||||
2. 使用 `OpenAI API Key` 请填写 `OPENAI_API_KEY` 字段 [(获取 apiKey)](https://platform.openai.com/overview)
|
||||
3. 使用 `Web API` 请填写 `OPENAI_ACCESS_TOKEN` 字段 [(获取 accessToken)](https://chat.openai.com/api/auth/session)
|
||||
4. 同时存在时以 `OpenAI API Key` 优先
|
||||
|
||||
反向代理:
|
||||
环境变量:
|
||||
|
||||
`ChatGPTUnofficialProxyAPI`时可用 [详情](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy)
|
||||
全部参数变量请查看或[这里](#环境变量)
|
||||
|
||||
```shell
|
||||
# service/.env
|
||||
API_REVERSE_PROXY=
|
||||
```
|
||||
/service/.env.example
|
||||
```
|
||||
|
||||
## 待实现路线
|
||||
@@ -69,6 +74,12 @@ API_REVERSE_PROXY=
|
||||
|
||||
[✓] 对代码等消息类型的格式化美化处理
|
||||
|
||||
[✓] 访问权限控制
|
||||
|
||||
[✓] 数据导入、导出
|
||||
|
||||
[✓] 保存消息到本地图片
|
||||
|
||||
[✓] 界面多语言
|
||||
|
||||
[✓] 界面主题
|
||||
@@ -79,7 +90,7 @@ API_REVERSE_PROXY=
|
||||
|
||||
### Node
|
||||
|
||||
`node` 需要 `^16 || ^18` 版本(`node >= 14` 需要安装 [fetch polyfill](https://github.com/developit/unfetch#usage-as-a-polyfill)),使用 [nvm](https://github.com/nvm-sh/nvm) 可管理本地多个 `node` 版本
|
||||
`node` 需要 `^16 || ^18 || ^19` 版本(`node >= 14` 需要安装 [fetch polyfill](https://github.com/developit/unfetch#usage-as-a-polyfill)),使用 [nvm](https://github.com/nvm-sh/nvm) 可管理本地多个 `node` 版本
|
||||
|
||||
```shell
|
||||
node -v
|
||||
@@ -137,17 +148,36 @@ pnpm start
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
## 环境变量
|
||||
|
||||
`API` 可用:
|
||||
|
||||
- `OPENAI_API_KEY` 和 `OPENAI_ACCESS_TOKEN` 二选一
|
||||
- `OPENAI_API_MODEL` 设置模型,可选,默认:`gpt-3.5-turbo`
|
||||
- `OPENAI_API_BASE_URL` 设置接口地址,可选,默认:`https://api.openai.com`
|
||||
- `OPENAI_API_DISABLE_DEBUG` 设置接口关闭 debug 日志,可选,默认:empty 不关闭
|
||||
|
||||
`ACCESS_TOKEN` 可用:
|
||||
|
||||
- `OPENAI_ACCESS_TOKEN` 和 `OPENAI_API_KEY` 二选一,同时存在时,`OPENAI_API_KEY` 优先
|
||||
- `API_REVERSE_PROXY` 设置反向代理,可选,默认:`https://bypass.churchless.tech/api/conversation`,[社区](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy)(注意:只有这两个是推荐,其他第三方来源,请自行甄别)
|
||||
|
||||
通用:
|
||||
|
||||
- `AUTH_SECRET_KEY` 访问权限密钥,可选
|
||||
- `MAX_REQUEST_PER_HOUR` 每小时最大请求次数,可选,默认无限
|
||||
- `TIMEOUT_MS` 超时,单位毫秒,可选
|
||||
- `SOCKS_PROXY_HOST` 和 `SOCKS_PROXY_PORT` 一起时生效,可选
|
||||
- `SOCKS_PROXY_PORT` 和 `SOCKS_PROXY_HOST` 一起时生效,可选
|
||||
- `HTTPS_PROXY` 支持 `http`,`https`, `socks5`,可选
|
||||
- `ALL_PROXY` 支持 `http`,`https`, `socks5`,可选
|
||||
|
||||
## 打包
|
||||
|
||||
### 使用 Docker
|
||||
|
||||
#### Docker 参数示例
|
||||
|
||||
- `OPENAI_API_KEY` 二选一
|
||||
- `OPENAI_ACCESS_TOKEN` 二选一,同时存在时,`OPENAI_API_KEY` 优先
|
||||
- `API_REVERSE_PROXY` 可选,设置 `OPENAI_ACCESS_TOKEN` 时可用 [参考](#介绍)
|
||||
- `TIMEOUT_MS` 超时,单位毫秒,可选
|
||||
|
||||

|
||||
|
||||
#### Docker build & Run
|
||||
@@ -156,10 +186,10 @@ pnpm dev
|
||||
docker build -t chatgpt-web .
|
||||
|
||||
# 前台运行
|
||||
docker run --name chatgpt-web --rm -it -p 3002:3002 --env OPENAI_API_KEY=your_api_key chatgpt-web
|
||||
docker run --name chatgpt-web --rm -it -p 127.0.0.1:3002:3002 --env OPENAI_API_KEY=your_api_key chatgpt-web
|
||||
|
||||
# 后台运行
|
||||
docker run --name chatgpt-web -d -p 3002:3002 --env OPENAI_API_KEY=your_api_key chatgpt-web
|
||||
docker run --name chatgpt-web -d -p 127.0.0.1:3002:3002 --env OPENAI_API_KEY=your_api_key chatgpt-web
|
||||
|
||||
# 运行地址
|
||||
http://localhost:3002/
|
||||
@@ -176,31 +206,57 @@ services:
|
||||
app:
|
||||
image: chenzhaoyu94/chatgpt-web # 总是使用 latest ,更新时重新 pull 该 tag 镜像即可
|
||||
ports:
|
||||
- 3002:3002
|
||||
- 127.0.0.1:3002:3002
|
||||
environment:
|
||||
# 二选一
|
||||
OPENAI_API_KEY: xxxxxx
|
||||
OPENAI_API_KEY: sk-xxx
|
||||
# 二选一
|
||||
OPENAI_ACCESS_TOKEN: xxxxxx
|
||||
OPENAI_ACCESS_TOKEN: xxx
|
||||
# API接口地址,可选,设置 OPENAI_API_KEY 时可用
|
||||
OPENAI_API_BASE_URL: xxx
|
||||
# API模型,可选,设置 OPENAI_API_KEY 时可用,https://platform.openai.com/docs/models
|
||||
# gpt-4, gpt-4-0314, gpt-4-32k, gpt-4-32k-0314, gpt-3.5-turbo, gpt-3.5-turbo-0301, text-davinci-003, text-davinci-002, code-davinci-002
|
||||
OPENAI_API_MODEL: xxx
|
||||
# 反向代理,可选
|
||||
API_REVERSE_PROXY: xxx
|
||||
# 访问权限密钥,可选
|
||||
AUTH_SECRET_KEY: xxx
|
||||
# 每小时最大请求次数,可选,默认无限
|
||||
MAX_REQUEST_PER_HOUR: 0
|
||||
# 超时,单位毫秒,可选
|
||||
TIMEOUT_MS: 60000
|
||||
# Socks代理,可选,和 SOCKS_PROXY_PORT 一起时生效
|
||||
SOCKS_PROXY_HOST: xxx
|
||||
# Socks代理端口,可选,和 SOCKS_PROXY_HOST 一起时生效
|
||||
SOCKS_PROXY_PORT: xxx
|
||||
# HTTPS 代理,可选,支持 http,https,socks5
|
||||
HTTPS_PROXY: http://xxx:7890
|
||||
```
|
||||
|
||||
- `OPENAI_API_BASE_URL` 可选,设置 `OPENAI_API_KEY` 时可用
|
||||
- `OPENAI_API_MODEL` 可选,设置 `OPENAI_API_KEY` 时可用
|
||||
### 使用 Railway 部署
|
||||
|
||||
[](https://railway.app/new/template/yytmgc)
|
||||
|
||||
#### Railway 环境变量
|
||||
|
||||
| 环境变量名称 | 必填 | 备注 |
|
||||
| --------------------------- | ---- | ----------------------- |
|
||||
| `PORT` | 必填 | 默认 `3002` |
|
||||
| `TIMEOUT_MS` | 可选 | 超时时间,单位毫秒, |
|
||||
| `OPENAI_API_KEY` | `OpenAI API` 二选一 | 使用 `OpenAI API` 所需的 `apiKey` [(获取 apiKey)](https://platform.openai.com/overview) |
|
||||
| `OPENAI_ACCESS_TOKEN` | `Web API` 二选一 | 使用 `Web API` 所需的 `accessToken` [(获取 accessToken)](https://chat.openai.com/api/auth/session) |
|
||||
| `API_REVERSE_PROXY` | 可选,`Web API` 时可用 | `Web API` 反向代理地址 [详情](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy) |
|
||||
| 环境变量名称 | 必填 | 备注 |
|
||||
| --------------------- | ---------------------- | -------------------------------------------------------------------------------------------------- |
|
||||
| `PORT` | 必填 | 默认 `3002`
|
||||
| `AUTH_SECRET_KEY` | 可选 | 访问权限密钥 |
|
||||
| `MAX_REQUEST_PER_HOUR` | 可选 | 每小时最大请求次数,可选,默认无限 |
|
||||
| `TIMEOUT_MS` | 可选 | 超时时间,单位毫秒 |
|
||||
| `OPENAI_API_KEY` | `OpenAI API` 二选一 | 使用 `OpenAI API` 所需的 `apiKey` [(获取 apiKey)](https://platform.openai.com/overview) |
|
||||
| `OPENAI_ACCESS_TOKEN` | `Web API` 二选一 | 使用 `Web API` 所需的 `accessToken` [(获取 accessToken)](https://chat.openai.com/api/auth/session) |
|
||||
| `OPENAI_API_BASE_URL` | 可选,`OpenAI API` 时可用 | `API`接口地址 |
|
||||
| `OPENAI_API_MODEL` | 可选,`OpenAI API` 时可用 | `API`模型 |
|
||||
| `API_REVERSE_PROXY` | 可选,`Web API` 时可用 | `Web API` 反向代理地址 [详情](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy) |
|
||||
| `SOCKS_PROXY_HOST` | 可选,和 `SOCKS_PROXY_PORT` 一起时生效 | Socks代理 |
|
||||
| `SOCKS_PROXY_PORT` | 可选,和 `SOCKS_PROXY_HOST` 一起时生效 | Socks代理端口 |
|
||||
| `SOCKS_PROXY_USERNAME` | 可选,和 `SOCKS_PROXY_HOST` 一起时生效 | Socks代理用户名 |
|
||||
| `SOCKS_PROXY_PASSWORD` | 可选,和 `SOCKS_PROXY_HOST` 一起时生效 | Socks代理密码 |
|
||||
| `HTTPS_PROXY` | 可选 | HTTPS 代理,支持 http,https, socks5 |
|
||||
| `ALL_PROXY` | 可选 | 所有代理 代理,支持 http,https, socks5 |
|
||||
|
||||
> 注意: `Railway` 修改环境变量会重新 `Deploy`
|
||||
|
||||
@@ -225,7 +281,7 @@ PS: 不进行打包,直接在服务器上运行 `pnpm start` 也可
|
||||
|
||||
#### 前端网页
|
||||
|
||||
1、修改根目录下 `.env` 内 `VITE_APP_API_BASE_URL` 为你的实际后端接口地址
|
||||
1、修改根目录下 `.env` 文件中的 `VITE_GLOB_API_URL` 为你的实际后端接口地址
|
||||
|
||||
2、根目录下运行以下命令,然后将 `dist` 文件夹内的文件复制到你网站服务的根目录下
|
||||
|
||||
@@ -248,6 +304,10 @@ Q: 文件保存时全部爆红?
|
||||
|
||||
A: `vscode` 请安装项目推荐插件,或手动安装 `Eslint` 插件。
|
||||
|
||||
Q: 前端没有打字机效果?
|
||||
|
||||
A: 一种可能原因是经过 Nginx 反向代理,开启了 buffer,则 Nginx 会尝试从后端缓冲一定大小的数据再发送给浏览器。请尝试在反代参数后添加 `proxy_buffering off;`,然后重载 Nginx。其他 web server 配置同理。
|
||||
|
||||
## 参与贡献
|
||||
|
||||
贡献之前请先阅读 [贡献指南](./CONTRIBUTING.md)
|
||||
|
||||
@@ -2,26 +2,46 @@ version: '3'
|
||||
|
||||
services:
|
||||
app:
|
||||
container_name: chatgpt-web
|
||||
image: chenzhaoyu94/chatgpt-web # 总是使用latest,更新时重新pull该tag镜像即可
|
||||
ports:
|
||||
- 3002:3002
|
||||
environment:
|
||||
# 二选一
|
||||
OPENAI_API_KEY: xxxx
|
||||
OPENAI_API_KEY:
|
||||
# 二选一
|
||||
OPENAI_ACCESS_TOKEN: xxxxxx
|
||||
OPENAI_ACCESS_TOKEN:
|
||||
# API接口地址,可选,设置 OPENAI_API_KEY 时可用
|
||||
OPENAI_API_BASE_URL:
|
||||
# API模型,可选,设置 OPENAI_API_KEY 时可用
|
||||
OPENAI_API_MODEL:
|
||||
# 反向代理,可选
|
||||
API_REVERSE_PROXY: xxx
|
||||
API_REVERSE_PROXY:
|
||||
# 访问权限密钥,可选
|
||||
AUTH_SECRET_KEY:
|
||||
# 每小时最大请求次数,可选,默认无限
|
||||
MAX_REQUEST_PER_HOUR: 0
|
||||
# 超时,单位毫秒,可选
|
||||
TIMEOUT_MS: 60000
|
||||
# Socks代理,可选,和 SOCKS_PROXY_PORT 一起时生效
|
||||
SOCKS_PROXY_HOST:
|
||||
# Socks代理端口,可选,和 SOCKS_PROXY_HOST 一起时生效
|
||||
SOCKS_PROXY_PORT:
|
||||
# Socks代理用户名,可选,和 SOCKS_PROXY_HOST & SOCKS_PROXY_PORT 一起时生效
|
||||
SOCKS_PROXY_USERNAME:
|
||||
# Socks代理密码,可选,和 SOCKS_PROXY_HOST & SOCKS_PROXY_PORT 一起时生效
|
||||
SOCKS_PROXY_PASSWORD:
|
||||
# HTTPS_PROXY 代理,可选
|
||||
HTTPS_PROXY:
|
||||
nginx:
|
||||
build: nginx
|
||||
image: chatgpt/nginx
|
||||
container_name: nginx
|
||||
image: nginx:alpine
|
||||
ports:
|
||||
- '80:80'
|
||||
expose:
|
||||
- '80'
|
||||
volumes:
|
||||
- ./nginx/html/:/etc/nginx/html/
|
||||
- ./nginx/html:/usr/share/nginx/html
|
||||
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf
|
||||
links:
|
||||
- app
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
FROM hub.c.163.com/library/nginx
|
||||
|
||||
MAINTAINER jo "tionsin@live.com"
|
||||
|
||||
RUN rm -rf /etc/nginx/conf.d/default.conf
|
||||
COPY ./nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY ./html/ /usr/share/nginx/html/
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
@@ -3,9 +3,9 @@ server {
|
||||
server_name localhost;
|
||||
charset utf-8;
|
||||
error_page 500 502 503 504 /50x.html;
|
||||
location = / {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html index.htm;
|
||||
location / {
|
||||
root /usr/share/nginx/html;
|
||||
try_files $uri /index.html;
|
||||
}
|
||||
|
||||
location /api {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
### docker-compose 部署教程
|
||||
- 将打包好的前端文件放到 `nginx/html` 目录下
|
||||
- ```shell
|
||||
# 打包启动
|
||||
docker-compose build
|
||||
# 启动
|
||||
docker-compose up -d
|
||||
```
|
||||
- ```shell
|
||||
|
||||
BIN
docs/c1-2.9.0.png
Normal file
|
After Width: | Height: | Size: 282 KiB |
BIN
docs/c1.png
|
Before Width: | Height: | Size: 410 KiB After Width: | Height: | Size: 96 KiB |
BIN
docs/c2-2.9.0.png
Normal file
|
After Width: | Height: | Size: 128 KiB |
BIN
docs/c2.png
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 78 KiB |
BIN
docs/cover.png
|
Before Width: | Height: | Size: 96 KiB |
BIN
docs/cover2.png
|
Before Width: | Height: | Size: 518 KiB |
@@ -3,6 +3,8 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<meta content="yes" name="apple-mobile-web-app-capable"/>
|
||||
<link rel="apple-touch-icon" href="/favicon.ico">
|
||||
<meta name="viewport"
|
||||
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover" />
|
||||
<title>ChatGPT Web</title>
|
||||
|
||||
9
kubernetes/README.md
Normal file
@@ -0,0 +1,9 @@
|
||||
## 增加一个Kubernetes的部署方式
|
||||
```
|
||||
kubectl apply -f deploy.yaml
|
||||
```
|
||||
|
||||
### 如果需要Ingress域名接入
|
||||
```
|
||||
kubectl apply -f ingress.yaml
|
||||
```
|
||||
66
kubernetes/deploy.yaml
Normal file
@@ -0,0 +1,66 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: chatgpt-web
|
||||
labels:
|
||||
app: chatgpt-web
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: chatgpt-web
|
||||
strategy:
|
||||
type: RollingUpdate
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: chatgpt-web
|
||||
spec:
|
||||
containers:
|
||||
- image: chenzhaoyu94/chatgpt-web
|
||||
name: chatgpt-web
|
||||
imagePullPolicy: Always
|
||||
ports:
|
||||
- containerPort: 3002
|
||||
env:
|
||||
- name: OPENAI_API_KEY
|
||||
value: sk-xxx
|
||||
- name: OPENAI_API_BASE_URL
|
||||
value: 'https://api.openai.com'
|
||||
- name: OPENAI_API_MODEL
|
||||
value: gpt-3.5-turbo
|
||||
- name: API_REVERSE_PROXY
|
||||
value: https://bypass.churchless.tech/api/conversation
|
||||
- name: AUTH_SECRET_KEY
|
||||
value: '123456'
|
||||
- name: TIMEOUT_MS
|
||||
value: '60000'
|
||||
- name: SOCKS_PROXY_HOST
|
||||
value: ''
|
||||
- name: SOCKS_PROXY_PORT
|
||||
value: ''
|
||||
- name: HTTPS_PROXY
|
||||
value: ''
|
||||
resources:
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 500Mi
|
||||
requests:
|
||||
cpu: 300m
|
||||
memory: 300Mi
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
labels:
|
||||
app: chatgpt-web
|
||||
name: chatgpt-web
|
||||
spec:
|
||||
ports:
|
||||
- name: chatgpt-web
|
||||
port: 3002
|
||||
protocol: TCP
|
||||
targetPort: 3002
|
||||
selector:
|
||||
app: chatgpt-web
|
||||
type: ClusterIP
|
||||
21
kubernetes/ingress.yaml
Normal file
@@ -0,0 +1,21 @@
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
annotations:
|
||||
kubernetes.io/ingress.class: nginx
|
||||
nginx.ingress.kubernetes.io/proxy-connect-timeout: '5'
|
||||
name: chatgpt-web
|
||||
spec:
|
||||
rules:
|
||||
- host: chatgpt.example.com
|
||||
http:
|
||||
paths:
|
||||
- backend:
|
||||
service:
|
||||
name: chatgpt-web
|
||||
port:
|
||||
number: 3002
|
||||
path: /
|
||||
pathType: ImplementationSpecific
|
||||
tls:
|
||||
- secretName: chatgpt-web-tls
|
||||
21
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "chatgpt-web",
|
||||
"version": "2.9.1",
|
||||
"version": "2.10.9",
|
||||
"private": false,
|
||||
"description": "ChatGPT Web",
|
||||
"author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>",
|
||||
@@ -23,11 +23,14 @@
|
||||
"common:prepare": "husky install"
|
||||
},
|
||||
"dependencies": {
|
||||
"@traptitech/markdown-it-katex": "^3.6.0",
|
||||
"@vueuse/core": "^9.13.0",
|
||||
"highlight.js": "^11.7.0",
|
||||
"marked": "^4.2.12",
|
||||
"html2canvas": "^1.4.1",
|
||||
"katex": "^0.16.4",
|
||||
"markdown-it": "^13.0.1",
|
||||
"naive-ui": "^2.34.3",
|
||||
"pinia": "^2.0.32",
|
||||
"pinia": "^2.0.33",
|
||||
"vue": "^3.2.47",
|
||||
"vue-i18n": "^9.2.2",
|
||||
"vue-router": "^4.1.6"
|
||||
@@ -38,8 +41,10 @@
|
||||
"@commitlint/config-conventional": "^17.4.4",
|
||||
"@iconify/vue": "^4.1.0",
|
||||
"@types/crypto-js": "^4.1.1",
|
||||
"@types/marked": "^4.0.8",
|
||||
"@types/node": "^18.14.4",
|
||||
"@types/katex": "^0.16.0",
|
||||
"@types/markdown-it": "^12.2.3",
|
||||
"@types/markdown-it-link-attributes": "^3.0.1",
|
||||
"@types/node": "^18.14.6",
|
||||
"@vitejs/plugin-vue": "^4.0.0",
|
||||
"autoprefixer": "^10.4.13",
|
||||
"axios": "^1.3.4",
|
||||
@@ -48,12 +53,14 @@
|
||||
"husky": "^8.0.3",
|
||||
"less": "^4.1.3",
|
||||
"lint-staged": "^13.1.2",
|
||||
"markdown-it-link-attributes": "^4.0.1",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"postcss": "^8.4.21",
|
||||
"rimraf": "^4.1.3",
|
||||
"rimraf": "^4.2.0",
|
||||
"tailwindcss": "^3.2.7",
|
||||
"typescript": "~4.9.5",
|
||||
"vite": "^4.1.4",
|
||||
"vite": "^4.2.0",
|
||||
"vite-plugin-pwa": "^0.14.4",
|
||||
"vue-tsc": "^1.2.0"
|
||||
},
|
||||
"lint-staged": {
|
||||
|
||||
3774
pnpm-lock.yaml
generated
BIN
public/favicon.ico
Normal file
|
After Width: | Height: | Size: 41 KiB |
BIN
public/pwa-192x192.png
Normal file
|
After Width: | Height: | Size: 7.2 KiB |
BIN
public/pwa-512x512.png
Normal file
|
After Width: | Height: | Size: 34 KiB |
11
service/.env
@@ -1,11 +0,0 @@
|
||||
# OpenAI API Key - https://platform.openai.com/overview
|
||||
OPENAI_API_KEY=
|
||||
|
||||
# change this to an `accessToken` extracted from the ChatGPT site's `https://chat.openai.com/api/auth/session` response
|
||||
OPENAI_ACCESS_TOKEN=
|
||||
|
||||
# Reverse Proxy
|
||||
API_REVERSE_PROXY=
|
||||
|
||||
# timeout
|
||||
TIMEOUT_MS=100000
|
||||
44
service/.env.example
Normal file
@@ -0,0 +1,44 @@
|
||||
# OpenAI API Key - https://platform.openai.com/overview
|
||||
OPENAI_API_KEY=
|
||||
|
||||
# change this to an `accessToken` extracted from the ChatGPT site's `https://chat.openai.com/api/auth/session` response
|
||||
OPENAI_ACCESS_TOKEN=
|
||||
|
||||
# OpenAI API Base URL - https://api.openai.com
|
||||
OPENAI_API_BASE_URL=
|
||||
|
||||
# OpenAI API Model - https://platform.openai.com/docs/models
|
||||
OPENAI_API_MODEL=
|
||||
|
||||
# set `true` to disable OpenAI API debug log
|
||||
OPENAI_API_DISABLE_DEBUG=
|
||||
|
||||
# Reverse Proxy - Available on accessToken
|
||||
# Default: https://bypass.churchless.tech/api/conversation
|
||||
# More: https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy
|
||||
API_REVERSE_PROXY=
|
||||
|
||||
# timeout
|
||||
TIMEOUT_MS=100000
|
||||
|
||||
# Rate Limit
|
||||
MAX_REQUEST_PER_HOUR=
|
||||
|
||||
# Secret key
|
||||
AUTH_SECRET_KEY=
|
||||
|
||||
# Socks Proxy Host
|
||||
SOCKS_PROXY_HOST=
|
||||
|
||||
# Socks Proxy Port
|
||||
SOCKS_PROXY_PORT=
|
||||
|
||||
# Socks Proxy Username
|
||||
SOCKS_PROXY_USERNAME=
|
||||
|
||||
# Socks Proxy Password
|
||||
SOCKS_PROXY_PASSWORD=
|
||||
|
||||
# HTTPS PROXY
|
||||
HTTPS_PROXY=
|
||||
|
||||
@@ -11,12 +11,12 @@
|
||||
"express"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^16 || ^18"
|
||||
"node": "^16 || ^18 || ^19"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "esno ./src/index.ts",
|
||||
"dev": "esno watch ./src/index.ts",
|
||||
"prod": "esno ./build/index.js",
|
||||
"prod": "node ./build/index.mjs",
|
||||
"build": "pnpm clean && tsup",
|
||||
"clean": "rimraf build",
|
||||
"lint": "eslint .",
|
||||
@@ -24,10 +24,13 @@
|
||||
"common:cleanup": "rimraf node_modules && rimraf pnpm-lock.yaml"
|
||||
},
|
||||
"dependencies": {
|
||||
"chatgpt": "^5.0.4",
|
||||
"axios": "^1.3.4",
|
||||
"chatgpt": "^5.2.2",
|
||||
"dotenv": "^16.0.3",
|
||||
"esno": "^0.16.3",
|
||||
"express": "^4.18.2",
|
||||
"express-rate-limit": "^6.7.0",
|
||||
"https-proxy-agent": "^5.0.1",
|
||||
"isomorphic-fetch": "^3.0.0",
|
||||
"node-fetch": "^3.3.0",
|
||||
"socks-proxy-agent": "^7.0.0"
|
||||
@@ -35,9 +38,9 @@
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^0.35.3",
|
||||
"@types/express": "^4.17.17",
|
||||
"@types/node": "^18.14.4",
|
||||
"@types/node": "^18.14.6",
|
||||
"eslint": "^8.35.0",
|
||||
"rimraf": "^4.1.3",
|
||||
"rimraf": "^4.3.0",
|
||||
"tsup": "^6.6.3",
|
||||
"typescript": "^4.9.5"
|
||||
}
|
||||
|
||||
1446
service/pnpm-lock.yaml
generated
@@ -1,98 +1,111 @@
|
||||
import * as dotenv from 'dotenv'
|
||||
import 'isomorphic-fetch'
|
||||
import type { ChatMessage, SendMessageOptions } from 'chatgpt'
|
||||
import type { ChatGPTAPIOptions, ChatMessage, SendMessageOptions } from 'chatgpt'
|
||||
import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt'
|
||||
import { SocksProxyAgent } from 'socks-proxy-agent'
|
||||
import httpsProxyAgent from 'https-proxy-agent'
|
||||
import fetch from 'node-fetch'
|
||||
import axios from 'axios'
|
||||
import { sendResponse } from '../utils'
|
||||
import type { ApiModel, ChatContext, ChatGPTAPIOptions, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
|
||||
import { isNotEmptyString } from '../utils/is'
|
||||
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
|
||||
import type { RequestOptions } from './types'
|
||||
|
||||
const { HttpsProxyAgent } = httpsProxyAgent
|
||||
|
||||
dotenv.config()
|
||||
|
||||
const ErrorCodeMessage: Record<string, string> = {
|
||||
401: '[OpenAI] 提供错误的API密钥 | Incorrect API key provided',
|
||||
403: '[OpenAI] 服务器拒绝访问,请稍后再试 | Server refused to access, please try again later',
|
||||
502: '[OpenAI] 错误的网关 | Bad Gateway',
|
||||
503: '[OpenAI] 服务器繁忙,请稍后再试 | Server is busy, please try again later',
|
||||
504: '[OpenAI] 网关超时 | Gateway Time-out',
|
||||
500: '[OpenAI] 服务器繁忙,请稍后再试 | Internal Server Error',
|
||||
}
|
||||
|
||||
const timeoutMs: number = !isNaN(+process.env.TIMEOUT_MS) ? +process.env.TIMEOUT_MS : 30 * 1000
|
||||
const disableDebug: boolean = process.env.OPENAI_API_DISABLE_DEBUG === 'true'
|
||||
|
||||
let apiModel: ApiModel
|
||||
|
||||
if (!process.env.OPENAI_API_KEY && !process.env.OPENAI_ACCESS_TOKEN)
|
||||
if (!isNotEmptyString(process.env.OPENAI_API_KEY) && !isNotEmptyString(process.env.OPENAI_ACCESS_TOKEN))
|
||||
throw new Error('Missing OPENAI_API_KEY or OPENAI_ACCESS_TOKEN environment variable')
|
||||
|
||||
let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
|
||||
|
||||
// To use ESM in CommonJS, you can use a dynamic import
|
||||
(async () => {
|
||||
// More Info: https://github.com/transitive-bullshit/chatgpt-api
|
||||
|
||||
if (process.env.OPENAI_API_KEY) {
|
||||
if (isNotEmptyString(process.env.OPENAI_API_KEY)) {
|
||||
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL
|
||||
const OPENAI_API_MODEL = process.env.OPENAI_API_MODEL
|
||||
const model = isNotEmptyString(OPENAI_API_MODEL) ? OPENAI_API_MODEL : 'gpt-3.5-turbo'
|
||||
|
||||
const options: ChatGPTAPIOptions = {
|
||||
apiKey: process.env.OPENAI_API_KEY,
|
||||
debug: false,
|
||||
completionParams: { model },
|
||||
debug: !disableDebug,
|
||||
}
|
||||
|
||||
// increase max token limit if use gpt-4
|
||||
if (model.toLowerCase().includes('gpt-4')) {
|
||||
// if use 32k model
|
||||
if (model.toLowerCase().includes('32k')) {
|
||||
options.maxModelTokens = 32768
|
||||
options.maxResponseTokens = 8192
|
||||
}
|
||||
else {
|
||||
options.maxModelTokens = 8192
|
||||
options.maxResponseTokens = 2048
|
||||
}
|
||||
}
|
||||
|
||||
if (isNotEmptyString(OPENAI_API_BASE_URL))
|
||||
options.apiBaseUrl = `${OPENAI_API_BASE_URL}/v1`
|
||||
|
||||
setupProxy(options)
|
||||
|
||||
api = new ChatGPTAPI({ ...options })
|
||||
apiModel = 'ChatGPTAPI'
|
||||
}
|
||||
else {
|
||||
const OPENAI_API_MODEL = process.env.OPENAI_API_MODEL
|
||||
const options: ChatGPTUnofficialProxyAPIOptions = {
|
||||
accessToken: process.env.OPENAI_ACCESS_TOKEN,
|
||||
debug: false,
|
||||
debug: !disableDebug,
|
||||
}
|
||||
|
||||
if (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) {
|
||||
const agent = new SocksProxyAgent({
|
||||
hostname: process.env.SOCKS_PROXY_HOST,
|
||||
port: process.env.SOCKS_PROXY_PORT,
|
||||
})
|
||||
options.fetch = (url, options) => {
|
||||
return fetch(url, { agent, ...options })
|
||||
}
|
||||
}
|
||||
if (isNotEmptyString(OPENAI_API_MODEL))
|
||||
options.model = OPENAI_API_MODEL
|
||||
|
||||
if (process.env.API_REVERSE_PROXY)
|
||||
options.apiReverseProxyUrl = process.env.API_REVERSE_PROXY
|
||||
options.apiReverseProxyUrl = isNotEmptyString(process.env.API_REVERSE_PROXY)
|
||||
? process.env.API_REVERSE_PROXY
|
||||
: 'https://bypass.churchless.tech/api/conversation'
|
||||
|
||||
api = new ChatGPTUnofficialProxyAPI({
|
||||
accessToken: process.env.OPENAI_ACCESS_TOKEN,
|
||||
...options,
|
||||
})
|
||||
setupProxy(options)
|
||||
|
||||
api = new ChatGPTUnofficialProxyAPI({ ...options })
|
||||
apiModel = 'ChatGPTUnofficialProxyAPI'
|
||||
}
|
||||
})()
|
||||
|
||||
async function chatReply(
|
||||
message: string,
|
||||
lastContext?: { conversationId?: string; parentMessageId?: string },
|
||||
) {
|
||||
if (!message)
|
||||
return sendResponse({ type: 'Fail', message: 'Message is empty' })
|
||||
|
||||
async function chatReplyProcess(options: RequestOptions) {
|
||||
const { message, lastContext, process, systemMessage } = options
|
||||
try {
|
||||
let options: SendMessageOptions = { timeoutMs }
|
||||
|
||||
if (lastContext)
|
||||
options = { ...lastContext }
|
||||
if (apiModel === 'ChatGPTAPI') {
|
||||
if (isNotEmptyString(systemMessage))
|
||||
options.systemMessage = systemMessage
|
||||
}
|
||||
|
||||
const response = await api.sendMessage(message, { ...options })
|
||||
|
||||
return sendResponse({ type: 'Success', data: response })
|
||||
}
|
||||
catch (error: any) {
|
||||
return sendResponse({ type: 'Fail', message: error.message })
|
||||
}
|
||||
}
|
||||
|
||||
async function chatReplyProcess(
|
||||
message: string,
|
||||
lastContext?: { conversationId?: string; parentMessageId?: string },
|
||||
process?: (chat: ChatMessage) => void,
|
||||
) {
|
||||
if (!message)
|
||||
return sendResponse({ type: 'Fail', message: 'Message is empty' })
|
||||
|
||||
try {
|
||||
let options: SendMessageOptions = { timeoutMs }
|
||||
|
||||
if (lastContext)
|
||||
options = { ...lastContext }
|
||||
if (lastContext != null) {
|
||||
if (apiModel === 'ChatGPTAPI')
|
||||
options.parentMessageId = lastContext.parentMessageId
|
||||
else
|
||||
options = { ...lastContext }
|
||||
}
|
||||
|
||||
const response = await api.sendMessage(message, {
|
||||
...options,
|
||||
@@ -104,22 +117,78 @@ async function chatReplyProcess(
|
||||
return sendResponse({ type: 'Success', data: response })
|
||||
}
|
||||
catch (error: any) {
|
||||
return sendResponse({ type: 'Fail', message: error.message })
|
||||
const code = error.statusCode
|
||||
global.console.log(error)
|
||||
if (Reflect.has(ErrorCodeMessage, code))
|
||||
return sendResponse({ type: 'Fail', message: ErrorCodeMessage[code] })
|
||||
return sendResponse({ type: 'Fail', message: error.message ?? 'Please check the back-end console' })
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchBalance() {
|
||||
const OPENAI_API_KEY = process.env.OPENAI_API_KEY
|
||||
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL
|
||||
|
||||
if (!isNotEmptyString(OPENAI_API_KEY))
|
||||
return Promise.resolve('-')
|
||||
|
||||
const API_BASE_URL = isNotEmptyString(OPENAI_API_BASE_URL)
|
||||
? OPENAI_API_BASE_URL
|
||||
: 'https://api.openai.com'
|
||||
|
||||
try {
|
||||
const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${OPENAI_API_KEY}` }
|
||||
const response = await axios.get(`${API_BASE_URL}/dashboard/billing/credit_grants`, { headers })
|
||||
const balance = response.data.total_available ?? 0
|
||||
return Promise.resolve(balance.toFixed(3))
|
||||
}
|
||||
catch {
|
||||
return Promise.resolve('-')
|
||||
}
|
||||
}
|
||||
|
||||
async function chatConfig() {
|
||||
return sendResponse({
|
||||
const balance = await fetchBalance()
|
||||
const reverseProxy = process.env.API_REVERSE_PROXY ?? '-'
|
||||
const httpsProxy = (process.env.HTTPS_PROXY || process.env.ALL_PROXY) ?? '-'
|
||||
const socksProxy = (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT)
|
||||
? (`${process.env.SOCKS_PROXY_HOST}:${process.env.SOCKS_PROXY_PORT}`)
|
||||
: '-'
|
||||
return sendResponse<ModelConfig>({
|
||||
type: 'Success',
|
||||
data: {
|
||||
apiModel,
|
||||
reverseProxy: process.env.API_REVERSE_PROXY,
|
||||
timeoutMs,
|
||||
socksProxy: (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) ? (`${process.env.SOCKS_PROXY_HOST}:${process.env.SOCKS_PROXY_PORT}`) : '-',
|
||||
} as ModelConfig,
|
||||
data: { apiModel, reverseProxy, timeoutMs, socksProxy, httpsProxy, balance },
|
||||
})
|
||||
}
|
||||
|
||||
function setupProxy(options: ChatGPTAPIOptions | ChatGPTUnofficialProxyAPIOptions) {
|
||||
if (isNotEmptyString(process.env.SOCKS_PROXY_HOST) && isNotEmptyString(process.env.SOCKS_PROXY_PORT)) {
|
||||
const agent = new SocksProxyAgent({
|
||||
hostname: process.env.SOCKS_PROXY_HOST,
|
||||
port: process.env.SOCKS_PROXY_PORT,
|
||||
userId: isNotEmptyString(process.env.SOCKS_PROXY_USERNAME) ? process.env.SOCKS_PROXY_USERNAME : undefined,
|
||||
password: isNotEmptyString(process.env.SOCKS_PROXY_PASSWORD) ? process.env.SOCKS_PROXY_PASSWORD : undefined,
|
||||
})
|
||||
options.fetch = (url, options) => {
|
||||
return fetch(url, { agent, ...options })
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (isNotEmptyString(process.env.HTTPS_PROXY) || isNotEmptyString(process.env.ALL_PROXY)) {
|
||||
const httpsProxy = process.env.HTTPS_PROXY || process.env.ALL_PROXY
|
||||
if (httpsProxy) {
|
||||
const agent = new HttpsProxyAgent(httpsProxy)
|
||||
options.fetch = (url, options) => {
|
||||
return fetch(url, { agent, ...options })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function currentModel(): ApiModel {
|
||||
return apiModel
|
||||
}
|
||||
|
||||
export type { ChatContext, ChatMessage }
|
||||
|
||||
export { chatReply, chatReplyProcess, chatConfig }
|
||||
export { chatReplyProcess, chatConfig, currentModel }
|
||||
|
||||
8
service/src/chatgpt/types.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import type { ChatMessage } from 'chatgpt'
|
||||
|
||||
export interface RequestOptions {
|
||||
message: string
|
||||
lastContext?: { conversationId?: string; parentMessageId?: string }
|
||||
process?: (chat: ChatMessage) => void
|
||||
systemMessage?: string
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import express from 'express'
|
||||
import type { ChatContext, ChatMessage } from './chatgpt'
|
||||
import { chatConfig, chatReply, chatReplyProcess } from './chatgpt'
|
||||
import type { RequestProps } from './types'
|
||||
import type { ChatMessage } from './chatgpt'
|
||||
import { chatConfig, chatReplyProcess, currentModel } from './chatgpt'
|
||||
import { auth } from './middleware/auth'
|
||||
import { limiter } from './middleware/limiter'
|
||||
import { isNotEmptyString } from './utils/is'
|
||||
|
||||
const app = express()
|
||||
const router = express.Router()
|
||||
@@ -10,31 +14,25 @@ app.use(express.json())
|
||||
|
||||
app.all('*', (_, res, next) => {
|
||||
res.header('Access-Control-Allow-Origin', '*')
|
||||
res.header('Access-Control-Allow-Headers', 'Content-Type')
|
||||
res.header('Access-Control-Allow-Headers', 'authorization, Content-Type')
|
||||
res.header('Access-Control-Allow-Methods', '*')
|
||||
next()
|
||||
})
|
||||
|
||||
router.post('/chat', async (req, res) => {
|
||||
try {
|
||||
const { prompt, options = {} } = req.body as { prompt: string; options?: ChatContext }
|
||||
const response = await chatReply(prompt, options)
|
||||
res.send(response)
|
||||
}
|
||||
catch (error) {
|
||||
res.send(error)
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/chat-process', async (req, res) => {
|
||||
router.post('/chat-process', [auth, limiter], async (req, res) => {
|
||||
res.setHeader('Content-type', 'application/octet-stream')
|
||||
|
||||
try {
|
||||
const { prompt, options = {} } = req.body as { prompt: string; options?: ChatContext }
|
||||
const { prompt, options = {}, systemMessage } = req.body as RequestProps
|
||||
let firstChunk = true
|
||||
await chatReplyProcess(prompt, options, (chat: ChatMessage) => {
|
||||
res.write(firstChunk ? JSON.stringify(chat) : `\n${JSON.stringify(chat)}`)
|
||||
firstChunk = false
|
||||
await chatReplyProcess({
|
||||
message: prompt,
|
||||
lastContext: options,
|
||||
process: (chat: ChatMessage) => {
|
||||
res.write(firstChunk ? JSON.stringify(chat) : `\n${JSON.stringify(chat)}`)
|
||||
firstChunk = false
|
||||
},
|
||||
systemMessage,
|
||||
})
|
||||
}
|
||||
catch (error) {
|
||||
@@ -45,7 +43,7 @@ router.post('/chat-process', async (req, res) => {
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/config', async (req, res) => {
|
||||
router.post('/config', auth, async (req, res) => {
|
||||
try {
|
||||
const response = await chatConfig()
|
||||
res.send(response)
|
||||
@@ -55,7 +53,35 @@ router.post('/config', async (req, res) => {
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/session', async (req, res) => {
|
||||
try {
|
||||
const AUTH_SECRET_KEY = process.env.AUTH_SECRET_KEY
|
||||
const hasAuth = isNotEmptyString(AUTH_SECRET_KEY)
|
||||
res.send({ status: 'Success', message: '', data: { auth: hasAuth, model: currentModel() } })
|
||||
}
|
||||
catch (error) {
|
||||
res.send({ status: 'Fail', message: error.message, data: null })
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/verify', async (req, res) => {
|
||||
try {
|
||||
const { token } = req.body as { token: string }
|
||||
if (!token)
|
||||
throw new Error('Secret key is empty')
|
||||
|
||||
if (process.env.AUTH_SECRET_KEY !== token)
|
||||
throw new Error('密钥无效 | Secret key is invalid')
|
||||
|
||||
res.send({ status: 'Success', message: 'Verify successfully', data: null })
|
||||
}
|
||||
catch (error) {
|
||||
res.send({ status: 'Fail', message: error.message, data: null })
|
||||
}
|
||||
})
|
||||
|
||||
app.use('', router)
|
||||
app.use('/api', router)
|
||||
app.set('trust proxy', 1)
|
||||
|
||||
app.listen(3002, () => globalThis.console.log('Server is running on port 3002'))
|
||||
|
||||
21
service/src/middleware/auth.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { isNotEmptyString } from '../utils/is'
|
||||
|
||||
const auth = async (req, res, next) => {
|
||||
const AUTH_SECRET_KEY = process.env.AUTH_SECRET_KEY
|
||||
if (isNotEmptyString(AUTH_SECRET_KEY)) {
|
||||
try {
|
||||
const Authorization = req.header('Authorization')
|
||||
if (!Authorization || Authorization.replace('Bearer ', '').trim() !== AUTH_SECRET_KEY.trim())
|
||||
throw new Error('Error: 无访问权限 | No access rights')
|
||||
next()
|
||||
}
|
||||
catch (error) {
|
||||
res.send({ status: 'Unauthorized', message: error.message ?? 'Please authenticate.', data: null })
|
||||
}
|
||||
}
|
||||
else {
|
||||
next()
|
||||
}
|
||||
}
|
||||
|
||||
export { auth }
|
||||
19
service/src/middleware/limiter.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { rateLimit } from 'express-rate-limit'
|
||||
import { isNotEmptyString } from '../utils/is'
|
||||
|
||||
const MAX_REQUEST_PER_HOUR = process.env.MAX_REQUEST_PER_HOUR
|
||||
|
||||
const maxCount = (isNotEmptyString(MAX_REQUEST_PER_HOUR) && !isNaN(Number(MAX_REQUEST_PER_HOUR)))
|
||||
? parseInt(MAX_REQUEST_PER_HOUR)
|
||||
: 0 // 0 means unlimited
|
||||
|
||||
const limiter = rateLimit({
|
||||
windowMs: 60 * 60 * 1000, // Maximum number of accesses within an hour
|
||||
max: maxCount,
|
||||
statusCode: 200, // 200 means success,but the message is 'Too many request from this IP in 1 hour'
|
||||
message: async (req, res) => {
|
||||
res.send({ status: 'Fail', message: 'Too many request from this IP in 1 hour', data: null })
|
||||
},
|
||||
})
|
||||
|
||||
export { limiter }
|
||||
@@ -1,16 +1,16 @@
|
||||
import type { FetchFn, openai } from 'chatgpt'
|
||||
import type { FetchFn } from 'chatgpt'
|
||||
|
||||
export interface RequestProps {
|
||||
prompt: string
|
||||
options?: ChatContext
|
||||
systemMessage: string
|
||||
}
|
||||
|
||||
export interface ChatContext {
|
||||
conversationId?: string
|
||||
parentMessageId?: string
|
||||
}
|
||||
|
||||
export interface ChatGPTAPIOptions {
|
||||
apiKey: string
|
||||
debug?: boolean
|
||||
completionParams?: Partial<openai.CompletionParams>
|
||||
}
|
||||
|
||||
export interface ChatGPTUnofficialProxyAPIOptions {
|
||||
accessToken: string
|
||||
apiReverseProxyUrl?: string
|
||||
@@ -25,6 +25,8 @@ export interface ModelConfig {
|
||||
reverseProxy?: string
|
||||
timeoutMs?: number
|
||||
socksProxy?: string
|
||||
httpsProxy?: string
|
||||
balance?: string
|
||||
}
|
||||
|
||||
export type ApiModel = 'ChatGPTAPI' | 'ChatGPTUnofficialProxyAPI' | undefined
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
interface SendResponseOptions {
|
||||
interface SendResponseOptions<T = any> {
|
||||
type: 'Success' | 'Fail'
|
||||
message?: string
|
||||
data?: any
|
||||
data?: T
|
||||
}
|
||||
|
||||
export function sendResponse(options: SendResponseOptions) {
|
||||
export function sendResponse<T>(options: SendResponseOptions<T>) {
|
||||
if (options.type === 'Success') {
|
||||
return Promise.resolve({
|
||||
message: options.message ?? null,
|
||||
|
||||
19
service/src/utils/is.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
export function isNumber<T extends number>(value: T | unknown): value is number {
|
||||
return Object.prototype.toString.call(value) === '[object Number]'
|
||||
}
|
||||
|
||||
export function isString<T extends string>(value: T | unknown): value is string {
|
||||
return Object.prototype.toString.call(value) === '[object String]'
|
||||
}
|
||||
|
||||
export function isNotEmptyString(value: any): boolean {
|
||||
return typeof value === 'string' && value.length > 0
|
||||
}
|
||||
|
||||
export function isBoolean<T extends boolean>(value: T | unknown): value is boolean {
|
||||
return Object.prototype.toString.call(value) === '[object Boolean]'
|
||||
}
|
||||
|
||||
export function isFunction<T extends (...args: any[]) => any | void | never>(value: T | unknown): value is T {
|
||||
return Object.prototype.toString.call(value) === '[object Function]'
|
||||
}
|
||||
@@ -4,7 +4,7 @@ export default defineConfig({
|
||||
entry: ['src/index.ts'],
|
||||
outDir: 'build',
|
||||
target: 'es2020',
|
||||
format: ['cjs'],
|
||||
format: ['esm'],
|
||||
splitting: false,
|
||||
sourcemap: true,
|
||||
minify: false,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { AxiosProgressEvent, GenericAbortSignal } from 'axios'
|
||||
import { post } from '@/utils/request'
|
||||
import { useSettingStore } from '@/store'
|
||||
|
||||
export function fetchChatAPI<T = any>(
|
||||
prompt: string,
|
||||
@@ -26,10 +27,25 @@ export function fetchChatAPIProcess<T = any>(
|
||||
signal?: GenericAbortSignal
|
||||
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void },
|
||||
) {
|
||||
const settingStore = useSettingStore()
|
||||
|
||||
return post<T>({
|
||||
url: '/chat-process',
|
||||
data: { prompt: params.prompt, options: params.options },
|
||||
data: { prompt: params.prompt, options: params.options, systemMessage: settingStore.systemMessage },
|
||||
signal: params.signal,
|
||||
onDownloadProgress: params.onDownloadProgress,
|
||||
})
|
||||
}
|
||||
|
||||
export function fetchSession<T>() {
|
||||
return post<T>({
|
||||
url: '/session',
|
||||
})
|
||||
}
|
||||
|
||||
export function fetchVerify<T>(token: string) {
|
||||
return post<T>({
|
||||
url: '/verify',
|
||||
data: { token },
|
||||
})
|
||||
}
|
||||
|
||||
14
src/assets/recommend.json
Normal file
@@ -0,0 +1,14 @@
|
||||
[
|
||||
{
|
||||
"key": "awesome-chatgpt-prompts-zh",
|
||||
"desc": "ChatGPT 中文调教指南",
|
||||
"downloadUrl": "https://raw.githubusercontent.com/PlexPt/awesome-chatgpt-prompts-zh/main/prompts-zh.json",
|
||||
"url": "https://github.com/PlexPt/awesome-chatgpt-prompts-zh"
|
||||
},
|
||||
{
|
||||
"key": "awesome-chatgpt-prompts-zh-TW",
|
||||
"desc": "ChatGPT 中文調教指南 (透過 OpenAI / OpenCC 協助,從簡體中文轉換為繁體中文的版本)",
|
||||
"downloadUrl": "https://raw.githubusercontent.com/PlexPt/awesome-chatgpt-prompts-zh/main/prompts-zh-TW.json",
|
||||
"url": "https://github.com/PlexPt/awesome-chatgpt-prompts-zh"
|
||||
}
|
||||
]
|
||||
480
src/components/common/PromptStore/index.vue
Normal file
@@ -0,0 +1,480 @@
|
||||
<script setup lang='ts'>
|
||||
import type { DataTableColumns } from 'naive-ui'
|
||||
import { computed, h, ref, watch } from 'vue'
|
||||
import { NButton, NCard, NDataTable, NDivider, NInput, NList, NListItem, NModal, NPopconfirm, NSpace, NTabPane, NTabs, NThing, useMessage } from 'naive-ui'
|
||||
import PromptRecommend from '../../../assets/recommend.json'
|
||||
import { SvgIcon } from '..'
|
||||
import { usePromptStore } from '@/store'
|
||||
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||
import { t } from '@/locales'
|
||||
|
||||
interface DataProps {
|
||||
renderKey: string
|
||||
renderValue: string
|
||||
key: string
|
||||
value: string
|
||||
}
|
||||
|
||||
interface Props {
|
||||
visible: boolean
|
||||
}
|
||||
|
||||
interface Emit {
|
||||
(e: 'update:visible', visible: boolean): void
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const emit = defineEmits<Emit>()
|
||||
|
||||
const message = useMessage()
|
||||
|
||||
const show = computed({
|
||||
get: () => props.visible,
|
||||
set: (visible: boolean) => emit('update:visible', visible),
|
||||
})
|
||||
|
||||
const showModal = ref(false)
|
||||
|
||||
const importLoading = ref(false)
|
||||
const exportLoading = ref(false)
|
||||
|
||||
const searchValue = ref<string>('')
|
||||
|
||||
// 移动端自适应相关
|
||||
const { isMobile } = useBasicLayout()
|
||||
|
||||
const promptStore = usePromptStore()
|
||||
|
||||
// Prompt在线导入推荐List,根据部署者喜好进行修改(assets/recommend.json)
|
||||
const promptRecommendList = PromptRecommend
|
||||
const promptList = ref<any>(promptStore.promptList)
|
||||
|
||||
// 用于添加修改的临时prompt参数
|
||||
const tempPromptKey = ref('')
|
||||
const tempPromptValue = ref('')
|
||||
|
||||
// Modal模式,根据不同模式渲染不同的Modal内容
|
||||
const modalMode = ref('')
|
||||
|
||||
// 这个是为了后期的修改Prompt内容考虑,因为要针对无uuid的list进行修改,且考虑到不能出现标题和内容的冲突,所以就需要一个临时item来记录一下
|
||||
const tempModifiedItem = ref<any>({})
|
||||
|
||||
// 添加修改导入都使用一个Modal, 临时修改内容占用tempPromptKey,切换状态前先将内容都清楚
|
||||
const changeShowModal = (mode: 'add' | 'modify' | 'local_import', selected = { key: '', value: '' }) => {
|
||||
if (mode === 'add') {
|
||||
tempPromptKey.value = ''
|
||||
tempPromptValue.value = ''
|
||||
}
|
||||
else if (mode === 'modify') {
|
||||
tempModifiedItem.value = { ...selected }
|
||||
tempPromptKey.value = selected.key
|
||||
tempPromptValue.value = selected.value
|
||||
}
|
||||
else if (mode === 'local_import') {
|
||||
tempPromptKey.value = 'local_import'
|
||||
tempPromptValue.value = ''
|
||||
}
|
||||
showModal.value = !showModal.value
|
||||
modalMode.value = mode
|
||||
}
|
||||
|
||||
// 在线导入相关
|
||||
const downloadURL = ref('')
|
||||
const downloadDisabled = computed(() => downloadURL.value.trim().length < 1)
|
||||
const setDownloadURL = (url: string) => {
|
||||
downloadURL.value = url
|
||||
}
|
||||
|
||||
// 控制 input 按钮
|
||||
const inputStatus = computed (() => tempPromptKey.value.trim().length < 1 || tempPromptValue.value.trim().length < 1)
|
||||
|
||||
// Prompt模板相关操作
|
||||
const addPromptTemplate = () => {
|
||||
for (const i of promptList.value) {
|
||||
if (i.key === tempPromptKey.value) {
|
||||
message.error(t('store.addRepeatTitleTips'))
|
||||
return
|
||||
}
|
||||
if (i.value === tempPromptValue.value) {
|
||||
message.error(t('store.addRepeatContentTips', { msg: tempPromptKey.value }))
|
||||
return
|
||||
}
|
||||
}
|
||||
promptList.value.unshift({ key: tempPromptKey.value, value: tempPromptValue.value } as never)
|
||||
message.success(t('common.addSuccess'))
|
||||
changeShowModal('add')
|
||||
}
|
||||
|
||||
const modifyPromptTemplate = () => {
|
||||
let index = 0
|
||||
|
||||
// 通过临时索引把待修改项摘出来
|
||||
for (const i of promptList.value) {
|
||||
if (i.key === tempModifiedItem.value.key && i.value === tempModifiedItem.value.value)
|
||||
break
|
||||
index = index + 1
|
||||
}
|
||||
|
||||
const tempList = promptList.value.filter((_: any, i: number) => i !== index)
|
||||
|
||||
// 搜索有冲突的部分
|
||||
for (const i of tempList) {
|
||||
if (i.key === tempPromptKey.value) {
|
||||
message.error(t('store.editRepeatTitleTips'))
|
||||
return
|
||||
}
|
||||
if (i.value === tempPromptValue.value) {
|
||||
message.error(t('store.editRepeatContentTips', { msg: i.key }))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
promptList.value = [{ key: tempPromptKey.value, value: tempPromptValue.value }, ...tempList] as never
|
||||
message.success(t('common.editSuccess'))
|
||||
changeShowModal('modify')
|
||||
}
|
||||
|
||||
const deletePromptTemplate = (row: { key: string; value: string }) => {
|
||||
promptList.value = [
|
||||
...promptList.value.filter((item: { key: string; value: string }) => item.key !== row.key),
|
||||
] as never
|
||||
message.success(t('common.deleteSuccess'))
|
||||
}
|
||||
|
||||
const clearPromptTemplate = () => {
|
||||
promptList.value = []
|
||||
message.success(t('common.clearSuccess'))
|
||||
}
|
||||
|
||||
const importPromptTemplate = (from = 'online') => {
|
||||
try {
|
||||
const jsonData = JSON.parse(tempPromptValue.value)
|
||||
let key = ''
|
||||
let value = ''
|
||||
// 可以扩展加入更多模板字典的key
|
||||
if ('key' in jsonData[0]) {
|
||||
key = 'key'
|
||||
value = 'value'
|
||||
}
|
||||
else if ('act' in jsonData[0]) {
|
||||
key = 'act'
|
||||
value = 'prompt'
|
||||
}
|
||||
else {
|
||||
// 不支持的字典的key防止导入 以免破坏prompt商店打开
|
||||
message.warning('prompt key not supported.')
|
||||
throw new Error('prompt key not supported.')
|
||||
}
|
||||
|
||||
for (const i of jsonData) {
|
||||
if (!(key in i) || !(value in i))
|
||||
throw new Error(t('store.importError'))
|
||||
let safe = true
|
||||
for (const j of promptList.value) {
|
||||
if (j.key === i[key]) {
|
||||
message.warning(t('store.importRepeatTitle', { msg: i[key] }))
|
||||
safe = false
|
||||
break
|
||||
}
|
||||
if (j.value === i[value]) {
|
||||
message.warning(t('store.importRepeatContent', { msg: i[key] }))
|
||||
safe = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if (safe)
|
||||
promptList.value.unshift({ key: i[key], value: i[value] } as never)
|
||||
}
|
||||
message.success(t('common.importSuccess'))
|
||||
}
|
||||
catch {
|
||||
message.error('JSON 格式错误,请检查 JSON 格式')
|
||||
}
|
||||
if (from === 'local')
|
||||
showModal.value = !showModal.value
|
||||
}
|
||||
|
||||
// 模板导出
|
||||
const exportPromptTemplate = () => {
|
||||
exportLoading.value = true
|
||||
const jsonDataStr = JSON.stringify(promptList.value)
|
||||
const blob = new Blob([jsonDataStr], { type: 'application/json' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = 'ChatGPTPromptTemplate.json'
|
||||
link.click()
|
||||
URL.revokeObjectURL(url)
|
||||
exportLoading.value = false
|
||||
}
|
||||
|
||||
// 模板在线导入
|
||||
const downloadPromptTemplate = async () => {
|
||||
try {
|
||||
importLoading.value = true
|
||||
const response = await fetch(downloadURL.value)
|
||||
const jsonData = await response.json()
|
||||
if ('key' in jsonData[0] && 'value' in jsonData[0])
|
||||
tempPromptValue.value = JSON.stringify(jsonData)
|
||||
if ('act' in jsonData[0] && 'prompt' in jsonData[0]) {
|
||||
const newJsonData = jsonData.map((item: { act: string; prompt: string }) => {
|
||||
return {
|
||||
key: item.act,
|
||||
value: item.prompt,
|
||||
}
|
||||
})
|
||||
tempPromptValue.value = JSON.stringify(newJsonData)
|
||||
}
|
||||
importPromptTemplate()
|
||||
downloadURL.value = ''
|
||||
}
|
||||
catch {
|
||||
message.error(t('store.downloadError'))
|
||||
downloadURL.value = ''
|
||||
}
|
||||
finally {
|
||||
importLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 移动端自适应相关
|
||||
const renderTemplate = () => {
|
||||
const [keyLimit, valueLimit] = isMobile.value ? [10, 30] : [15, 50]
|
||||
|
||||
return promptList.value.map((item: { key: string; value: string }) => {
|
||||
return {
|
||||
renderKey: item.key.length <= keyLimit ? item.key : `${item.key.substring(0, keyLimit)}...`,
|
||||
renderValue: item.value.length <= valueLimit ? item.value : `${item.value.substring(0, valueLimit)}...`,
|
||||
key: item.key,
|
||||
value: item.value,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const pagination = computed(() => {
|
||||
const [pageSize, pageSlot] = isMobile.value ? [6, 5] : [7, 15]
|
||||
return {
|
||||
pageSize, pageSlot,
|
||||
}
|
||||
})
|
||||
|
||||
// table相关
|
||||
const createColumns = (): DataTableColumns<DataProps> => {
|
||||
return [
|
||||
{
|
||||
title: t('store.title'),
|
||||
key: 'renderKey',
|
||||
},
|
||||
{
|
||||
title: t('store.description'),
|
||||
key: 'renderValue',
|
||||
},
|
||||
{
|
||||
title: t('common.action'),
|
||||
key: 'actions',
|
||||
width: 100,
|
||||
align: 'center',
|
||||
render(row) {
|
||||
return h('div', { class: 'flex items-center flex-col gap-2' }, {
|
||||
default: () => [h(
|
||||
NButton,
|
||||
{
|
||||
tertiary: true,
|
||||
size: 'small',
|
||||
type: 'info',
|
||||
onClick: () => changeShowModal('modify', row),
|
||||
},
|
||||
{ default: () => t('common.edit') },
|
||||
),
|
||||
h(
|
||||
NButton,
|
||||
{
|
||||
tertiary: true,
|
||||
size: 'small',
|
||||
type: 'error',
|
||||
onClick: () => deletePromptTemplate(row),
|
||||
},
|
||||
{ default: () => t('common.delete') },
|
||||
),
|
||||
],
|
||||
})
|
||||
},
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
const columns = createColumns()
|
||||
|
||||
watch(
|
||||
() => promptList,
|
||||
() => {
|
||||
promptStore.updatePromptList(promptList.value)
|
||||
},
|
||||
{ deep: true },
|
||||
)
|
||||
|
||||
const dataSource = computed(() => {
|
||||
const data = renderTemplate()
|
||||
const value = searchValue.value
|
||||
if (value && value !== '') {
|
||||
return data.filter((item: DataProps) => {
|
||||
return item.renderKey.includes(value) || item.renderValue.includes(value)
|
||||
})
|
||||
}
|
||||
return data
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NModal v-model:show="show" style="width: 90%; max-width: 900px;" preset="card">
|
||||
<div class="space-y-4">
|
||||
<NTabs type="segment">
|
||||
<NTabPane name="local" :tab="$t('store.local')">
|
||||
<div
|
||||
class="flex gap-3 mb-4"
|
||||
:class="[isMobile ? 'flex-col' : 'flex-row justify-between']"
|
||||
>
|
||||
<div class="flex items-center space-x-4">
|
||||
<NButton
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="changeShowModal('add')"
|
||||
>
|
||||
{{ $t('common.add') }}
|
||||
</NButton>
|
||||
<NButton
|
||||
size="small"
|
||||
@click="changeShowModal('local_import')"
|
||||
>
|
||||
{{ $t('common.import') }}
|
||||
</NButton>
|
||||
<NButton
|
||||
size="small"
|
||||
:loading="exportLoading"
|
||||
@click="exportPromptTemplate()"
|
||||
>
|
||||
{{ $t('common.export') }}
|
||||
</NButton>
|
||||
<NPopconfirm @positive-click="clearPromptTemplate">
|
||||
<template #trigger>
|
||||
<NButton size="small">
|
||||
{{ $t('common.clear') }}
|
||||
</NButton>
|
||||
</template>
|
||||
{{ $t('store.clearStoreConfirm') }}
|
||||
</NPopconfirm>
|
||||
</div>
|
||||
<div class="flex items-center">
|
||||
<NInput v-model:value="searchValue" style="width: 100%" />
|
||||
</div>
|
||||
</div>
|
||||
<NDataTable
|
||||
v-if="!isMobile"
|
||||
:max-height="400"
|
||||
:columns="columns"
|
||||
:data="dataSource"
|
||||
:pagination="pagination"
|
||||
:bordered="false"
|
||||
/>
|
||||
<NList v-if="isMobile" style="max-height: 400px; overflow-y: auto;">
|
||||
<NListItem v-for="(item, index) of dataSource" :key="index">
|
||||
<NThing :title="item.renderKey" :description="item.renderValue" />
|
||||
<template #suffix>
|
||||
<div class="flex flex-col items-center gap-2">
|
||||
<NButton tertiary size="small" type="info" @click="changeShowModal('modify', item)">
|
||||
{{ t('common.edit') }}
|
||||
</NButton>
|
||||
<NButton tertiary size="small" type="error" @click="deletePromptTemplate(item)">
|
||||
{{ t('common.delete') }}
|
||||
</NButton>
|
||||
</div>
|
||||
</template>
|
||||
</NListItem>
|
||||
</NList>
|
||||
</NTabPane>
|
||||
<NTabPane name="download" :tab="$t('store.online')">
|
||||
<p class="mb-4">
|
||||
{{ $t('store.onlineImportWarning') }}
|
||||
</p>
|
||||
<div class="flex items-center gap-4">
|
||||
<NInput v-model:value="downloadURL" placeholder="" />
|
||||
<NButton
|
||||
strong
|
||||
secondary
|
||||
:disabled="downloadDisabled"
|
||||
:loading="importLoading"
|
||||
@click="downloadPromptTemplate()"
|
||||
>
|
||||
{{ $t('common.download') }}
|
||||
</NButton>
|
||||
</div>
|
||||
<NDivider />
|
||||
<div class="max-h-[360px] overflow-y-auto space-y-4">
|
||||
<NCard
|
||||
v-for="info in promptRecommendList"
|
||||
:key="info.key" :title="info.key"
|
||||
:bordered="true"
|
||||
embedded
|
||||
>
|
||||
<p
|
||||
class="overflow-hidden text-ellipsis whitespace-nowrap"
|
||||
:title="info.desc"
|
||||
>
|
||||
{{ info.desc }}
|
||||
</p>
|
||||
<template #footer>
|
||||
<div class="flex items-center justify-end space-x-4">
|
||||
<NButton text>
|
||||
<a
|
||||
:href="info.url"
|
||||
target="_blank"
|
||||
>
|
||||
<SvgIcon class="text-xl" icon="ri:link" />
|
||||
</a>
|
||||
</NButton>
|
||||
<NButton text @click="setDownloadURL(info.downloadUrl) ">
|
||||
<SvgIcon class="text-xl" icon="ri:add-fill" />
|
||||
</NButton>
|
||||
</div>
|
||||
</template>
|
||||
</NCard>
|
||||
</div>
|
||||
</NTabPane>
|
||||
</NTabs>
|
||||
</div>
|
||||
</NModal>
|
||||
|
||||
<NModal v-model:show="showModal" style="width: 90%; max-width: 600px;" preset="card">
|
||||
<NSpace v-if="modalMode === 'add' || modalMode === 'modify'" vertical>
|
||||
{{ t('store.title') }}
|
||||
<NInput v-model:value="tempPromptKey" />
|
||||
{{ t('store.description') }}
|
||||
<NInput v-model:value="tempPromptValue" type="textarea" />
|
||||
<NButton
|
||||
block
|
||||
type="primary"
|
||||
:disabled="inputStatus"
|
||||
@click="() => { modalMode === 'add' ? addPromptTemplate() : modifyPromptTemplate() }"
|
||||
>
|
||||
{{ t('common.confirm') }}
|
||||
</NButton>
|
||||
</NSpace>
|
||||
<NSpace v-if="modalMode === 'local_import'" vertical>
|
||||
<NInput
|
||||
v-model:value="tempPromptValue"
|
||||
:placeholder="t('store.importPlaceholder')"
|
||||
:autosize="{ minRows: 3, maxRows: 15 }"
|
||||
type="textarea"
|
||||
/>
|
||||
<NButton
|
||||
block
|
||||
type="primary"
|
||||
:disabled="inputStatus"
|
||||
@click="() => { importPromptTemplate('local') }"
|
||||
>
|
||||
{{ t('common.import') }}
|
||||
</NButton>
|
||||
</NSpace>
|
||||
</NModal>
|
||||
</template>
|
||||
@@ -1,20 +1,27 @@
|
||||
<script setup lang='ts'>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { NSpin } from 'naive-ui'
|
||||
import { fetchChatConfig } from '@/api'
|
||||
import pkg from '@/../package.json'
|
||||
import { useAuthStore } from '@/store'
|
||||
|
||||
interface ConfigState {
|
||||
timeoutMs?: number
|
||||
reverseProxy?: string
|
||||
apiModel?: string
|
||||
socksProxy?: string
|
||||
httpsProxy?: string
|
||||
balance?: string
|
||||
}
|
||||
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const loading = ref(false)
|
||||
|
||||
const config = ref<ConfigState>()
|
||||
|
||||
const isChatGPTAPI = computed<boolean>(() => !!authStore.isChatGPTAPI)
|
||||
|
||||
async function fetchConfig() {
|
||||
try {
|
||||
loading.value = true
|
||||
@@ -54,9 +61,15 @@ onMounted(() => {
|
||||
</p>
|
||||
</div>
|
||||
<p>{{ $t("setting.api") }}:{{ config?.apiModel ?? '-' }}</p>
|
||||
<p>{{ $t("setting.reverseProxy") }}:{{ config?.reverseProxy ?? '-' }}</p>
|
||||
<p v-if="isChatGPTAPI">
|
||||
{{ $t("setting.balance") }}:{{ config?.balance ?? '-' }}
|
||||
</p>
|
||||
<p v-if="!isChatGPTAPI">
|
||||
{{ $t("setting.reverseProxy") }}:{{ config?.reverseProxy ?? '-' }}
|
||||
</p>
|
||||
<p>{{ $t("setting.timeout") }}:{{ config?.timeoutMs ?? '-' }}</p>
|
||||
<p>{{ $t("setting.socks") }}:{{ config?.socksProxy ?? '-' }}</p>
|
||||
<p>{{ $t("setting.httpsProxy") }}:{{ config?.httpsProxy ?? '-' }}</p>
|
||||
</div>
|
||||
</NSpin>
|
||||
</template>
|
||||
|
||||
46
src/components/common/Setting/Advanced.vue
Normal file
@@ -0,0 +1,46 @@
|
||||
<script lang="ts" setup>
|
||||
import { ref } from 'vue'
|
||||
import { NButton, NInput, useMessage } from 'naive-ui'
|
||||
import { useSettingStore } from '@/store'
|
||||
import type { SettingsState } from '@/store/modules/settings/helper'
|
||||
import { t } from '@/locales'
|
||||
|
||||
const settingStore = useSettingStore()
|
||||
|
||||
const ms = useMessage()
|
||||
|
||||
const systemMessage = ref(settingStore.systemMessage ?? '')
|
||||
|
||||
function updateSettings(options: Partial<SettingsState>) {
|
||||
settingStore.updateSetting(options)
|
||||
ms.success(t('common.success'))
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
settingStore.resetSetting()
|
||||
ms.success(t('common.success'))
|
||||
window.location.reload()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="p-4 space-y-5 min-h-[200px]">
|
||||
<div class="space-y-6">
|
||||
<div class="flex items-center space-x-4">
|
||||
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.role') }}</span>
|
||||
<div class="flex-1">
|
||||
<NInput v-model:value="systemMessage" type="textarea" :autosize="{ minRows: 1, maxRows: 4 }" />
|
||||
</div>
|
||||
<NButton size="tiny" text type="primary" @click="updateSettings({ systemMessage })">
|
||||
{{ $t('common.save') }}
|
||||
</NButton>
|
||||
</div>
|
||||
<div class="flex items-center space-x-4">
|
||||
<span class="flex-shrink-0 w-[100px]"> </span>
|
||||
<NButton size="small" @click="handleReset">
|
||||
{{ $t('common.reset') }}
|
||||
</NButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,21 +1,19 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import { NButton, NInput, useMessage } from 'naive-ui'
|
||||
import { NButton, NInput, NPopconfirm, NSelect, useMessage } from 'naive-ui'
|
||||
import type { Language, Theme } from '@/store/modules/app/helper'
|
||||
import { SvgIcon } from '@/components/common'
|
||||
import { useAppStore, useUserStore } from '@/store'
|
||||
import type { UserInfo } from '@/store/modules/user/helper'
|
||||
import { getCurrentDate } from '@/utils/functions'
|
||||
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||
import { t } from '@/locales'
|
||||
|
||||
interface Emit {
|
||||
(event: 'update'): void
|
||||
}
|
||||
|
||||
const emit = defineEmits<Emit>()
|
||||
|
||||
const appStore = useAppStore()
|
||||
const userStore = useUserStore()
|
||||
|
||||
const { isMobile } = useBasicLayout()
|
||||
|
||||
const ms = useMessage()
|
||||
|
||||
const theme = computed(() => appStore.theme)
|
||||
@@ -56,7 +54,8 @@ const themeOptions: { label: string; key: Theme; icon: string }[] = [
|
||||
]
|
||||
|
||||
const languageOptions: { label: string; key: Language; value: Language }[] = [
|
||||
{ label: '中文', key: 'zh-CN', value: 'zh-CN' },
|
||||
{ label: '简体中文', key: 'zh-CN', value: 'zh-CN' },
|
||||
{ label: '繁體中文', key: 'zh-TW', value: 'zh-TW' },
|
||||
{ label: 'English', key: 'en-US', value: 'en-US' },
|
||||
]
|
||||
|
||||
@@ -68,7 +67,56 @@ function updateUserInfo(options: Partial<UserInfo>) {
|
||||
function handleReset() {
|
||||
userStore.resetUserInfo()
|
||||
ms.success(t('common.success'))
|
||||
emit('update')
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
function exportData(): void {
|
||||
const date = getCurrentDate()
|
||||
const data: string = localStorage.getItem('chatStorage') || '{}'
|
||||
const jsonString: string = JSON.stringify(JSON.parse(data), null, 2)
|
||||
const blob: Blob = new Blob([jsonString], { type: 'application/json' })
|
||||
const url: string = URL.createObjectURL(blob)
|
||||
const link: HTMLAnchorElement = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = `chat-store_${date}.json`
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
}
|
||||
|
||||
function importData(event: Event): void {
|
||||
const target = event.target as HTMLInputElement
|
||||
if (!target || !target.files)
|
||||
return
|
||||
|
||||
const file: File = target.files[0]
|
||||
if (!file)
|
||||
return
|
||||
|
||||
const reader: FileReader = new FileReader()
|
||||
reader.onload = () => {
|
||||
try {
|
||||
const data = JSON.parse(reader.result as string)
|
||||
localStorage.setItem('chatStorage', JSON.stringify(data))
|
||||
ms.success(t('common.success'))
|
||||
location.reload()
|
||||
}
|
||||
catch (error) {
|
||||
ms.error(t('common.invalidFileFormat'))
|
||||
}
|
||||
}
|
||||
reader.readAsText(file)
|
||||
}
|
||||
|
||||
function clearData(): void {
|
||||
localStorage.removeItem('chatStorage')
|
||||
location.reload()
|
||||
}
|
||||
|
||||
function handleImportButtonClick(): void {
|
||||
const fileInput = document.getElementById('fileInput') as HTMLElement
|
||||
if (fileInput)
|
||||
fileInput.click()
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -102,44 +150,74 @@ function handleReset() {
|
||||
{{ $t('common.save') }}
|
||||
</NButton>
|
||||
</div>
|
||||
<div class="flex items-center space-x-4">
|
||||
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.resetUserInfo') }}</span>
|
||||
<NButton text type="primary" @click="handleReset">
|
||||
{{ $t('common.reset') }}
|
||||
</NButton>
|
||||
<div
|
||||
class="flex items-center space-x-4"
|
||||
:class="isMobile && 'items-start'"
|
||||
>
|
||||
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.chatHistory') }}</span>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-4">
|
||||
<NButton size="small" @click="exportData">
|
||||
<template #icon>
|
||||
<SvgIcon icon="ri:download-2-fill" />
|
||||
</template>
|
||||
{{ $t('common.export') }}
|
||||
</NButton>
|
||||
|
||||
<input id="fileInput" type="file" style="display:none" @change="importData">
|
||||
<NButton size="small" @click="handleImportButtonClick">
|
||||
<template #icon>
|
||||
<SvgIcon icon="ri:upload-2-fill" />
|
||||
</template>
|
||||
{{ $t('common.import') }}
|
||||
</NButton>
|
||||
|
||||
<NPopconfirm placement="bottom" @positive-click="clearData">
|
||||
<template #trigger>
|
||||
<NButton size="small">
|
||||
<template #icon>
|
||||
<SvgIcon icon="ri:close-circle-line" />
|
||||
</template>
|
||||
{{ $t('common.clear') }}
|
||||
</NButton>
|
||||
</template>
|
||||
{{ $t('chat.clearHistoryConfirm') }}
|
||||
</NPopconfirm>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center space-x-4">
|
||||
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.theme') }}</span>
|
||||
<div class="flex items-center space-x-4">
|
||||
<div class="flex flex-wrap items-center gap-4">
|
||||
<template v-for="item of themeOptions" :key="item.key">
|
||||
<a
|
||||
class="flex items-center justify-center h-8 px-4 border rounded-md cursor-pointer dark:border-neutral-700"
|
||||
:class="item.key === theme && ['bg-[#4ca85e]', 'border-[#4ca85e]', 'text-white']"
|
||||
<NButton
|
||||
size="small"
|
||||
:type="item.key === theme ? 'primary' : undefined"
|
||||
@click="appStore.setTheme(item.key)"
|
||||
>
|
||||
<span class="text-xl">
|
||||
<template #icon>
|
||||
<SvgIcon :icon="item.icon" />
|
||||
</span>
|
||||
</a>
|
||||
</template>
|
||||
</NButton>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center space-x-4">
|
||||
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.language') }}</span>
|
||||
<div class="flex items-center space-x-4">
|
||||
<template v-for="item of languageOptions" :key="item.key">
|
||||
<a
|
||||
class="flex items-center justify-center h-8 px-4 border rounded-md cursor-pointer dark:border-neutral-700"
|
||||
:class="item.key === language && ['bg-[#4ca85e]', 'border-[#4ca85e]', 'text-white']"
|
||||
@click="appStore.setLanguage(item.key)"
|
||||
>
|
||||
<span class="text-sm">
|
||||
{{ item.label }}
|
||||
</span>
|
||||
</a>
|
||||
</template>
|
||||
<div class="flex flex-wrap items-center gap-4">
|
||||
<NSelect
|
||||
style="width: 140px"
|
||||
:value="language"
|
||||
:options="languageOptions"
|
||||
@update-value="value => appStore.setLanguage(value)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center space-x-4">
|
||||
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.resetUserInfo') }}</span>
|
||||
<NButton size="small" @click="handleReset">
|
||||
{{ $t('common.reset') }}
|
||||
</NButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
<script setup lang='ts'>
|
||||
import { computed, ref } from 'vue'
|
||||
import { NCard, NModal, NTabPane, NTabs } from 'naive-ui'
|
||||
import { NModal, NTabPane, NTabs } from 'naive-ui'
|
||||
import General from './General.vue'
|
||||
import Advanced from './Advanced.vue'
|
||||
import About from './About.vue'
|
||||
import { useAuthStore } from '@/store'
|
||||
import { SvgIcon } from '@/components/common'
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const emit = defineEmits<Emit>()
|
||||
|
||||
interface Props {
|
||||
visible: boolean
|
||||
}
|
||||
@@ -17,9 +15,15 @@ interface Emit {
|
||||
(e: 'update:visible', visible: boolean): void
|
||||
}
|
||||
|
||||
const active = ref('General')
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const reload = ref(false)
|
||||
const emit = defineEmits<Emit>()
|
||||
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const isChatGPTAPI = computed<boolean>(() => !!authStore.isChatGPTAPI)
|
||||
|
||||
const active = ref('General')
|
||||
|
||||
const show = computed({
|
||||
get() {
|
||||
@@ -29,18 +33,11 @@ const show = computed({
|
||||
emit('update:visible', visible)
|
||||
},
|
||||
})
|
||||
|
||||
function handleReload() {
|
||||
reload.value = true
|
||||
setTimeout(() => {
|
||||
reload.value = false
|
||||
}, 0)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NModal v-model:show="show" :auto-focus="false">
|
||||
<NCard role="dialog" aria-modal="true" :bordered="false" style="width: 100%; max-width: 640px">
|
||||
<NModal v-model:show="show" :auto-focus="false" preset="card" style="width: 95%; max-width: 640px">
|
||||
<div>
|
||||
<NTabs v-model:value="active" type="line" animated>
|
||||
<NTabPane name="General" tab="General">
|
||||
<template #tab>
|
||||
@@ -48,7 +45,16 @@ function handleReload() {
|
||||
<span class="ml-2">{{ $t('setting.general') }}</span>
|
||||
</template>
|
||||
<div class="min-h-[100px]">
|
||||
<General v-if="!reload" @update="handleReload" />
|
||||
<General />
|
||||
</div>
|
||||
</NTabPane>
|
||||
<NTabPane v-if="isChatGPTAPI" name="Advanced" tab="Advanced">
|
||||
<template #tab>
|
||||
<SvgIcon class="text-lg" icon="ri:equalizer-line" />
|
||||
<span class="ml-2">{{ $t('setting.advanced') }}</span>
|
||||
</template>
|
||||
<div class="min-h-[100px]">
|
||||
<Advanced />
|
||||
</div>
|
||||
</NTabPane>
|
||||
<NTabPane name="Config" tab="Config">
|
||||
@@ -59,6 +65,6 @@ function handleReload() {
|
||||
<About />
|
||||
</NTabPane>
|
||||
</NTabs>
|
||||
</NCard>
|
||||
</div>
|
||||
</NModal>
|
||||
</template>
|
||||
|
||||
@@ -11,8 +11,8 @@ const userInfo = computed(() => userStore.userInfo)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex items-center">
|
||||
<div class="w-10 h-10 overflow-hidden rounded-full">
|
||||
<div class="flex items-center overflow-hidden">
|
||||
<div class="w-10 h-10 overflow-hidden rounded-full shrink-0">
|
||||
<template v-if="isString(userInfo.avatar) && userInfo.avatar.length > 0">
|
||||
<NAvatar
|
||||
size="large"
|
||||
@@ -25,11 +25,11 @@ const userInfo = computed(() => userStore.userInfo)
|
||||
<NAvatar size="large" round :src="defaultAvatar" />
|
||||
</template>
|
||||
</div>
|
||||
<div class="ml-2">
|
||||
<h2 class="font-bold text-md">
|
||||
<div class="flex-1 min-w-0 ml-2">
|
||||
<h2 class="overflow-hidden font-bold text-md text-ellipsis whitespace-nowrap">
|
||||
{{ userInfo.name ?? 'ChenZhaoYu' }}
|
||||
</h2>
|
||||
<p class="text-xs text-gray-500">
|
||||
<p class="overflow-hidden text-xs text-gray-500 text-ellipsis whitespace-nowrap">
|
||||
<span
|
||||
v-if="isString(userInfo.description) && userInfo.description !== ''"
|
||||
v-html="userInfo.description"
|
||||
|
||||
@@ -3,5 +3,6 @@ import NaiveProvider from './NaiveProvider/index.vue'
|
||||
import SvgIcon from './SvgIcon/index.vue'
|
||||
import UserAvatar from './UserAvatar/index.vue'
|
||||
import Setting from './Setting/index.vue'
|
||||
import PromptStore from './PromptStore/index.vue'
|
||||
|
||||
export { HoverButton, NaiveProvider, SvgIcon, UserAvatar, Setting }
|
||||
export { HoverButton, NaiveProvider, SvgIcon, UserAvatar, Setting, PromptStore }
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import type { App, Directive } from 'vue'
|
||||
import hljs from 'highlight.js'
|
||||
import { includeCode } from '@/utils/format'
|
||||
|
||||
hljs.configure({ ignoreUnescapedHTML: true })
|
||||
|
||||
function highlightCode(el: HTMLElement) {
|
||||
if (includeCode(el.textContent))
|
||||
hljs.highlightBlock(el)
|
||||
}
|
||||
|
||||
export default function setupHighlightDirective(app: App) {
|
||||
const highLightDirective: Directive<HTMLElement> = {
|
||||
mounted(el: HTMLElement) {
|
||||
highlightCode(el)
|
||||
},
|
||||
updated(el: HTMLElement) {
|
||||
highlightCode(el)
|
||||
},
|
||||
}
|
||||
|
||||
app.directive('highlight', highLightDirective)
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import type { App } from 'vue'
|
||||
import setupHighlightDirective from './highlight'
|
||||
|
||||
export function setupDirectives(app: App) {
|
||||
setupHighlightDirective(app)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { computed } from 'vue'
|
||||
import { enUS, zhCN } from 'naive-ui'
|
||||
import { enUS, zhCN, zhTW } from 'naive-ui'
|
||||
import { useAppStore } from '@/store'
|
||||
import { setLocale } from '@/locales'
|
||||
|
||||
@@ -14,6 +14,9 @@ export function useLanguage() {
|
||||
case 'zh-CN':
|
||||
setLocale('zh-CN')
|
||||
return zhCN
|
||||
case 'zh-TW':
|
||||
setLocale('zh-TW')
|
||||
return zhTW
|
||||
default:
|
||||
setLocale('zh-CN')
|
||||
return enUS
|
||||
|
||||
|
Before Width: | Height: | Size: 19 KiB |
5
src/icons/403.vue
Normal file
5
src/icons/500.vue
Normal file
@@ -1,16 +1,34 @@
|
||||
export default {
|
||||
common: {
|
||||
add: 'Add',
|
||||
addSuccess: 'Add Success',
|
||||
edit: 'Edit',
|
||||
editSuccess: 'Edit Success',
|
||||
delete: 'Delete',
|
||||
deleteSuccess: 'Delete Success',
|
||||
save: 'Save',
|
||||
saveSuccess: 'Save Success',
|
||||
reset: 'Reset',
|
||||
action: 'Action',
|
||||
export: 'Export',
|
||||
exportSuccess: 'Export Success',
|
||||
import: 'Import',
|
||||
importSuccess: 'Import Success',
|
||||
clear: 'Clear',
|
||||
clearSuccess: 'Clear Success',
|
||||
yes: 'Yes',
|
||||
no: 'No',
|
||||
confirm: 'Confirm',
|
||||
download: 'Download',
|
||||
noData: 'No Data',
|
||||
wrong: 'Something went wrong, please try again later.',
|
||||
success: 'Success',
|
||||
failed: 'Failed',
|
||||
verify: 'Verify',
|
||||
unauthorizedTips: 'Unauthorized, please verify first.',
|
||||
},
|
||||
chat: {
|
||||
newChatButton: 'New Chat',
|
||||
placeholder: 'Ask me anything...(Shift + Enter = line break)',
|
||||
placeholderMobile: 'Ask me anything...',
|
||||
copy: 'Copy',
|
||||
@@ -18,24 +36,56 @@ export default {
|
||||
copyCode: 'Copy Code',
|
||||
clearChat: 'Clear Chat',
|
||||
clearChatConfirm: 'Are you sure to clear this chat?',
|
||||
exportImage: 'Export Image',
|
||||
exportImageConfirm: 'Are you sure to export this chat to png?',
|
||||
exportSuccess: 'Export Success',
|
||||
exportFailed: 'Export Failed',
|
||||
usingContext: 'Context Mode',
|
||||
turnOnContext: 'In the current mode, sending messages will carry previous chat records.',
|
||||
turnOffContext: 'In the current mode, sending messages will not carry previous chat records.',
|
||||
deleteMessage: 'Delete Message',
|
||||
deleteMessageConfirm: 'Are you sure to delete this message?',
|
||||
deleteHistoryConfirm: 'Are you sure to clear this history?',
|
||||
clearHistoryConfirm: 'Are you sure to clear chat history?',
|
||||
preview: 'Preview',
|
||||
showRawText: 'Show as raw text',
|
||||
},
|
||||
setting: {
|
||||
setting: 'Setting',
|
||||
general: 'General',
|
||||
advanced: 'Advanced',
|
||||
config: 'Config',
|
||||
avatarLink: 'Avatar Link',
|
||||
name: 'Name',
|
||||
description: 'Description',
|
||||
role: 'Role',
|
||||
resetUserInfo: 'Reset UserInfo',
|
||||
chatHistory: 'ChatHistory',
|
||||
theme: 'Theme',
|
||||
language: 'Language',
|
||||
api: 'API',
|
||||
reverseProxy: 'Reverse Proxy',
|
||||
timeout: 'Timeout',
|
||||
socks: 'Socks',
|
||||
httpsProxy: 'HTTPS Proxy',
|
||||
balance: 'API Balance',
|
||||
},
|
||||
store: {
|
||||
siderButton: 'Prompt Store',
|
||||
local: 'Local',
|
||||
online: 'Online',
|
||||
title: 'Title',
|
||||
description: 'Description',
|
||||
clearStoreConfirm: 'Whether to clear the data?',
|
||||
importPlaceholder: 'Please paste the JSON data here',
|
||||
addRepeatTitleTips: 'Title duplicate, please re-enter',
|
||||
addRepeatContentTips: 'Content duplicate: {msg}, please re-enter',
|
||||
editRepeatTitleTips: 'Title conflict, please revise',
|
||||
editRepeatContentTips: 'Content conflict {msg} , please re-modify',
|
||||
importError: 'Key value mismatch',
|
||||
importRepeatTitle: 'Title repeatedly skipped: {msg}',
|
||||
importRepeatContent: 'Content is repeatedly skipped: {msg}',
|
||||
onlineImportWarning: 'Note: Please check the JSON file source!',
|
||||
downloadError: 'Please check the network status and JSON file validity',
|
||||
},
|
||||
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { App } from 'vue'
|
||||
import { createI18n } from 'vue-i18n'
|
||||
import en from './en-US'
|
||||
import cn from './zh-CN'
|
||||
import enUS from './en-US'
|
||||
import zhCN from './zh-CN'
|
||||
import zhTW from './zh-TW'
|
||||
import { useAppStoreWithOut } from '@/store/modules/app'
|
||||
import type { Language } from '@/store/modules/app/helper'
|
||||
|
||||
@@ -14,14 +15,13 @@ const i18n = createI18n({
|
||||
fallbackLocale: 'en-US',
|
||||
allowComposition: true,
|
||||
messages: {
|
||||
'en-US': en,
|
||||
'zh-CN': cn,
|
||||
'en-US': enUS,
|
||||
'zh-CN': zhCN,
|
||||
'zh-TW': zhTW,
|
||||
},
|
||||
})
|
||||
|
||||
export function t(key: string) {
|
||||
return i18n.global.t(key)
|
||||
}
|
||||
export const t = i18n.global.t
|
||||
|
||||
export function setLocale(locale: Language) {
|
||||
i18n.global.locale = locale
|
||||
|
||||
@@ -1,41 +1,91 @@
|
||||
export default {
|
||||
common: {
|
||||
add: '添加',
|
||||
addSuccess: '添加成功',
|
||||
edit: '编辑',
|
||||
editSuccess: '编辑成功',
|
||||
delete: '删除',
|
||||
deleteSuccess: '删除成功',
|
||||
save: '保存',
|
||||
saveSuccess: '保存成功',
|
||||
reset: '重置',
|
||||
action: '操作',
|
||||
export: '导出',
|
||||
exportSuccess: '导出成功',
|
||||
import: '导入',
|
||||
importSuccess: '导入成功',
|
||||
clear: '清空',
|
||||
clearSuccess: '清空成功',
|
||||
yes: '是',
|
||||
no: '否',
|
||||
confirm: '确定',
|
||||
download: '下载',
|
||||
noData: '暂无数据',
|
||||
wrong: '好像出错了,请稍后再试。',
|
||||
success: '操作成功',
|
||||
failed: '操作失败',
|
||||
verify: '验证',
|
||||
unauthorizedTips: '未经授权,请先进行验证。',
|
||||
},
|
||||
chat: {
|
||||
placeholder: '来说点什么...(Shift + Enter = 换行)',
|
||||
newChatButton: '新建聊天',
|
||||
placeholder: '来说点什么吧...(Shift + Enter = 换行)',
|
||||
placeholderMobile: '来说点什么...',
|
||||
copy: '复制',
|
||||
copied: '复制成功',
|
||||
copyCode: '复制代码',
|
||||
clearChat: '清空会话',
|
||||
clearChatConfirm: '是否清空会话?',
|
||||
exportImage: '保存会话到图片',
|
||||
exportImageConfirm: '是否将会话保存为图片?',
|
||||
exportSuccess: '保存成功',
|
||||
exportFailed: '保存失败',
|
||||
usingContext: '上下文模式',
|
||||
turnOnContext: '当前模式下, 发送消息会携带之前的聊天记录',
|
||||
turnOffContext: '当前模式下, 发送消息不会携带之前的聊天记录',
|
||||
deleteMessage: '删除消息',
|
||||
deleteMessageConfirm: '是否删除此消息?',
|
||||
deleteHistoryConfirm: '确定删除此记录?',
|
||||
clearHistoryConfirm: '确定清空聊天记录?',
|
||||
preview: '预览',
|
||||
showRawText: '显示原文',
|
||||
},
|
||||
setting: {
|
||||
setting: '设置',
|
||||
general: '总览',
|
||||
advanced: '高级',
|
||||
config: '配置',
|
||||
avatarLink: '头像链接',
|
||||
name: '名称',
|
||||
description: '描述',
|
||||
role: '角色设定',
|
||||
resetUserInfo: '重置用户信息',
|
||||
chatHistory: '聊天记录',
|
||||
theme: '主题',
|
||||
language: '语言',
|
||||
api: 'API',
|
||||
reverseProxy: '反向代理',
|
||||
timeout: '超时',
|
||||
socks: 'Socks',
|
||||
httpsProxy: 'HTTPS Proxy',
|
||||
balance: 'API余额',
|
||||
},
|
||||
store: {
|
||||
siderButton: '提示词商店',
|
||||
local: '本地',
|
||||
online: '在线',
|
||||
title: '标题',
|
||||
description: '描述',
|
||||
clearStoreConfirm: '是否清空数据?',
|
||||
importPlaceholder: '请粘贴 JSON 数据到此处',
|
||||
addRepeatTitleTips: '标题重复,请重新输入',
|
||||
addRepeatContentTips: '内容重复:{msg},请重新输入',
|
||||
editRepeatTitleTips: '标题冲突,请重新修改',
|
||||
editRepeatContentTips: '内容冲突{msg} ,请重新修改',
|
||||
importError: '键值不匹配',
|
||||
importRepeatTitle: '标题重复跳过:{msg}',
|
||||
importRepeatContent: '内容重复跳过:{msg}',
|
||||
onlineImportWarning: '注意:请检查 JSON 文件来源!',
|
||||
downloadError: '请检查网络状态与 JSON 文件有效性',
|
||||
},
|
||||
|
||||
}
|
||||
|
||||
91
src/locales/zh-TW.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
export default {
|
||||
common: {
|
||||
add: '新增',
|
||||
addSuccess: '新增成功',
|
||||
edit: '編輯',
|
||||
editSuccess: '編輯成功',
|
||||
delete: '刪除',
|
||||
deleteSuccess: '刪除成功',
|
||||
save: '儲存',
|
||||
saveSuccess: '儲存成功',
|
||||
reset: '重設',
|
||||
action: '操作',
|
||||
export: '匯出',
|
||||
exportSuccess: '匯出成功',
|
||||
import: '匯入',
|
||||
importSuccess: '匯入成功',
|
||||
clear: '清除',
|
||||
clearSuccess: '清除成功',
|
||||
yes: '是',
|
||||
no: '否',
|
||||
confirm: '確認',
|
||||
download: '下載',
|
||||
noData: '目前無資料',
|
||||
wrong: '發生錯誤,請稍後再試。',
|
||||
success: '操作成功',
|
||||
failed: '操作失敗',
|
||||
verify: '驗證',
|
||||
unauthorizedTips: '未經授權,請先進行驗證。',
|
||||
},
|
||||
chat: {
|
||||
newChatButton: '新建對話',
|
||||
placeholder: '來說點什麼...(Shift + Enter = 換行)',
|
||||
placeholderMobile: '來說點什麼...',
|
||||
copy: '複製',
|
||||
copied: '複製成功',
|
||||
copyCode: '複製代碼',
|
||||
clearChat: '清除對話',
|
||||
clearChatConfirm: '是否清空對話?',
|
||||
exportImage: '儲存對話為圖片',
|
||||
exportImageConfirm: '是否將對話儲存為圖片?',
|
||||
exportSuccess: '儲存成功',
|
||||
exportFailed: '儲存失敗',
|
||||
usingContext: '上下文模式',
|
||||
turnOnContext: '啟用上下文模式,在此模式下,發送訊息會包含之前的聊天記錄。',
|
||||
turnOffContext: '關閉上下文模式,在此模式下,發送訊息不會包含之前的聊天記錄。',
|
||||
deleteMessage: '刪除訊息',
|
||||
deleteMessageConfirm: '是否刪除此訊息?',
|
||||
deleteHistoryConfirm: '確定刪除此紀錄?',
|
||||
clearHistoryConfirm: '確定清除紀錄?',
|
||||
preview: '預覽',
|
||||
showRawText: '顯示原文',
|
||||
},
|
||||
setting: {
|
||||
setting: '設定',
|
||||
general: '總覽',
|
||||
advanced: '高級',
|
||||
config: '設定',
|
||||
avatarLink: '頭貼連結',
|
||||
name: '名稱',
|
||||
description: '描述',
|
||||
role: '角色設定',
|
||||
resetUserInfo: '重設使用者資訊',
|
||||
chatHistory: '紀錄',
|
||||
theme: '主題',
|
||||
language: '語言',
|
||||
api: 'API',
|
||||
reverseProxy: '反向代理',
|
||||
timeout: '逾時',
|
||||
socks: 'Socks',
|
||||
httpsProxy: 'HTTPS Proxy',
|
||||
balance: 'API余額',
|
||||
},
|
||||
store: {
|
||||
siderButton: '提示詞商店',
|
||||
local: '本機',
|
||||
online: '線上',
|
||||
title: '標題',
|
||||
description: '描述',
|
||||
clearStoreConfirm: '是否清除資料?',
|
||||
importPlaceholder: '請將 JSON 資料貼在此處',
|
||||
addRepeatTitleTips: '標題重複,請重新輸入',
|
||||
addRepeatContentTips: '內容重複:{msg},請重新輸入',
|
||||
editRepeatTitleTips: '標題衝突,請重新修改',
|
||||
editRepeatContentTips: '內容衝突{msg} ,請重新修改',
|
||||
importError: '鍵值不符合',
|
||||
importRepeatTitle: '因標題重複跳過:{msg}',
|
||||
importRepeatContent: '因內容重複跳過:{msg}',
|
||||
onlineImportWarning: '注意:請檢查 JSON 檔案來源!',
|
||||
downloadError: '請檢查網路狀態與 JSON 檔案有效性',
|
||||
},
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import { setupDirectives } from './directives'
|
||||
import { setupI18n } from './locales'
|
||||
import { setupAssets } from './plugins'
|
||||
import { setupAssets, setupScrollbarStyle } from './plugins'
|
||||
import { setupStore } from './store'
|
||||
import { setupRouter } from './router'
|
||||
|
||||
@@ -10,9 +9,9 @@ async function bootstrap() {
|
||||
const app = createApp(App)
|
||||
setupAssets()
|
||||
|
||||
setupStore(app)
|
||||
setupScrollbarStyle()
|
||||
|
||||
setupDirectives(app)
|
||||
setupStore(app)
|
||||
|
||||
setupI18n(app)
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'katex/dist/katex.min.css'
|
||||
import '@/styles/lib/tailwind.css'
|
||||
import '@/styles/lib/highlight.less'
|
||||
import '@/styles/lib/github-markdown.less'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import setupAssets from './assets'
|
||||
import setupScrollbarStyle from './scrollbarStyle'
|
||||
|
||||
export { setupAssets }
|
||||
export { setupAssets, setupScrollbarStyle }
|
||||
|
||||
28
src/plugins/scrollbarStyle.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { darkTheme, lightTheme } from 'naive-ui'
|
||||
|
||||
const setupScrollbarStyle = () => {
|
||||
const style = document.createElement('style')
|
||||
const styleContent = `
|
||||
::-webkit-scrollbar {
|
||||
background-color: transparent;
|
||||
width: ${lightTheme.Scrollbar.common?.scrollbarWidth};
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: ${lightTheme.Scrollbar.common?.scrollbarColor};
|
||||
border-radius: ${lightTheme.Scrollbar.common?.scrollbarBorderRadius};
|
||||
}
|
||||
html.dark ::-webkit-scrollbar {
|
||||
background-color: transparent;
|
||||
width: ${darkTheme.Scrollbar.common?.scrollbarWidth};
|
||||
}
|
||||
html.dark ::-webkit-scrollbar-thumb {
|
||||
background-color: ${darkTheme.Scrollbar.common?.scrollbarColor};
|
||||
border-radius: ${darkTheme.Scrollbar.common?.scrollbarBorderRadius};
|
||||
}
|
||||
`
|
||||
|
||||
style.innerHTML = styleContent
|
||||
document.head.appendChild(style)
|
||||
}
|
||||
|
||||
export default setupScrollbarStyle
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { App } from 'vue'
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
import { createRouter, createWebHashHistory } from 'vue-router'
|
||||
import { setupPageGuard } from './permission'
|
||||
import { ChatLayout } from '@/views/chat/layout'
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
@@ -18,18 +19,18 @@ const routes: RouteRecordRaw[] = [
|
||||
],
|
||||
},
|
||||
|
||||
{
|
||||
path: '/403',
|
||||
name: '403',
|
||||
component: () => import('@/views/exception/403/index.vue'),
|
||||
},
|
||||
|
||||
{
|
||||
path: '/404',
|
||||
name: '404',
|
||||
component: () => import('@/views/exception/404/index.vue'),
|
||||
},
|
||||
|
||||
{
|
||||
path: '/500',
|
||||
name: '500',
|
||||
component: () => import('@/views/exception/500/index.vue'),
|
||||
},
|
||||
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
name: 'notFound',
|
||||
@@ -43,6 +44,8 @@ export const router = createRouter({
|
||||
scrollBehavior: () => ({ left: 0, top: 0 }),
|
||||
})
|
||||
|
||||
setupPageGuard(router)
|
||||
|
||||
export async function setupRouter(app: App) {
|
||||
app.use(router)
|
||||
await router.isReady()
|
||||
|
||||
28
src/router/permission.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import type { Router } from 'vue-router'
|
||||
import { useAuthStoreWithout } from '@/store/modules/auth'
|
||||
|
||||
export function setupPageGuard(router: Router) {
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
const authStore = useAuthStoreWithout()
|
||||
if (!authStore.session) {
|
||||
try {
|
||||
const data = await authStore.getSession()
|
||||
if (String(data.auth) === 'false' && authStore.token)
|
||||
authStore.removeToken()
|
||||
if (to.path === '/500')
|
||||
next({ name: 'Root' })
|
||||
else
|
||||
next()
|
||||
}
|
||||
catch (error) {
|
||||
if (to.path !== '/500')
|
||||
next({ name: '500' })
|
||||
else
|
||||
next()
|
||||
}
|
||||
}
|
||||
else {
|
||||
next()
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -4,7 +4,7 @@ const LOCAL_NAME = 'appSetting'
|
||||
|
||||
export type Theme = 'light' | 'dark' | 'auto'
|
||||
|
||||
export type Language = 'zh-CN' | 'en-US'
|
||||
export type Language = 'zh-CN' | 'zh-TW' | 'en-US'
|
||||
|
||||
export interface AppState {
|
||||
siderCollapsed: boolean
|
||||
|
||||
15
src/store/modules/auth/helper.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { ss } from '@/utils/storage'
|
||||
|
||||
const LOCAL_NAME = 'SECRET_TOKEN'
|
||||
|
||||
export function getToken() {
|
||||
return ss.get(LOCAL_NAME)
|
||||
}
|
||||
|
||||
export function setToken(token: string) {
|
||||
return ss.set(LOCAL_NAME, token)
|
||||
}
|
||||
|
||||
export function removeToken() {
|
||||
return ss.remove(LOCAL_NAME)
|
||||
}
|
||||
54
src/store/modules/auth/index.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { getToken, removeToken, setToken } from './helper'
|
||||
import { store } from '@/store'
|
||||
import { fetchSession } from '@/api'
|
||||
|
||||
interface SessionResponse {
|
||||
auth: boolean
|
||||
model: 'ChatGPTAPI' | 'ChatGPTUnofficialProxyAPI'
|
||||
}
|
||||
|
||||
export interface AuthState {
|
||||
token: string | undefined
|
||||
session: SessionResponse | null
|
||||
}
|
||||
|
||||
export const useAuthStore = defineStore('auth-store', {
|
||||
state: (): AuthState => ({
|
||||
token: getToken(),
|
||||
session: null,
|
||||
}),
|
||||
|
||||
getters: {
|
||||
isChatGPTAPI(state): boolean {
|
||||
return state.session?.model === 'ChatGPTAPI'
|
||||
},
|
||||
},
|
||||
|
||||
actions: {
|
||||
async getSession() {
|
||||
try {
|
||||
const { data } = await fetchSession<SessionResponse>()
|
||||
this.session = { ...data }
|
||||
return Promise.resolve(data)
|
||||
}
|
||||
catch (error) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
},
|
||||
|
||||
setToken(token: string) {
|
||||
this.token = token
|
||||
setToken(token)
|
||||
},
|
||||
|
||||
removeToken() {
|
||||
this.token = undefined
|
||||
removeToken()
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export function useAuthStoreWithout() {
|
||||
return useAuthStore(store)
|
||||
}
|
||||
@@ -3,13 +3,18 @@ import { ss } from '@/utils/storage'
|
||||
const LOCAL_NAME = 'chatStorage'
|
||||
|
||||
export function defaultState(): Chat.ChatState {
|
||||
const uuid = Date.now()
|
||||
return { active: uuid, history: [{ uuid, title: 'New Chat', isEdit: false }], chat: [{ uuid, data: [] }] }
|
||||
const uuid = 1002
|
||||
return {
|
||||
active: uuid,
|
||||
usingContext: true,
|
||||
history: [{ uuid, title: 'New Chat', isEdit: false }],
|
||||
chat: [{ uuid, data: [] }],
|
||||
}
|
||||
}
|
||||
|
||||
export function getLocalState(): Chat.ChatState {
|
||||
const localState = ss.get(LOCAL_NAME)
|
||||
return localState ?? defaultState()
|
||||
return { ...defaultState(), ...localState }
|
||||
}
|
||||
|
||||
export function setLocalState(state: Chat.ChatState) {
|
||||
|
||||
@@ -23,6 +23,11 @@ export const useChatStore = defineStore('chat-store', {
|
||||
},
|
||||
|
||||
actions: {
|
||||
setUsingContext(context: boolean) {
|
||||
this.usingContext = context
|
||||
this.recordState()
|
||||
},
|
||||
|
||||
addHistory(history: Chat.History, chatData: Chat.Chat[] = []) {
|
||||
this.history.unshift(history)
|
||||
this.chat.unshift({ uuid: history.uuid, data: chatData })
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
export * from './app'
|
||||
export * from './chat'
|
||||
export * from './user'
|
||||
export * from './prompt'
|
||||
export * from './settings'
|
||||
export * from './auth'
|
||||
|
||||
18
src/store/modules/prompt/helper.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { ss } from '@/utils/storage'
|
||||
|
||||
const LOCAL_NAME = 'promptStore'
|
||||
|
||||
export type PromptList = []
|
||||
|
||||
export interface PromptStore {
|
||||
promptList: PromptList
|
||||
}
|
||||
|
||||
export function getLocalPromptList(): PromptStore {
|
||||
const promptStore: PromptStore | undefined = ss.get(LOCAL_NAME)
|
||||
return promptStore ?? { promptList: [] }
|
||||
}
|
||||
|
||||
export function setLocalPromptList(promptStore: PromptStore): void {
|
||||
ss.set(LOCAL_NAME, promptStore)
|
||||
}
|
||||
17
src/store/modules/prompt/index.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { PromptStore } from './helper'
|
||||
import { getLocalPromptList, setLocalPromptList } from './helper'
|
||||
|
||||
export const usePromptStore = defineStore('prompt-store', {
|
||||
state: (): PromptStore => getLocalPromptList(),
|
||||
|
||||
actions: {
|
||||
updatePromptList(promptList: []) {
|
||||
this.$patch({ promptList })
|
||||
setLocalPromptList({ promptList })
|
||||
},
|
||||
getPromptList() {
|
||||
return this.$state
|
||||
},
|
||||
},
|
||||
})
|
||||
26
src/store/modules/settings/helper.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { ss } from '@/utils/storage'
|
||||
|
||||
const LOCAL_NAME = 'settingsStorage'
|
||||
|
||||
export interface SettingsState {
|
||||
systemMessage: string
|
||||
}
|
||||
|
||||
export function defaultSetting(): SettingsState {
|
||||
return {
|
||||
systemMessage: 'You are ChatGPT, a large language model trained by OpenAI. Follow the user\'s instructions carefully. Respond using markdown.',
|
||||
}
|
||||
}
|
||||
|
||||
export function getLocalState(): SettingsState {
|
||||
const localSetting: SettingsState | undefined = ss.get(LOCAL_NAME)
|
||||
return { ...defaultSetting(), ...localSetting }
|
||||
}
|
||||
|
||||
export function setLocalState(setting: SettingsState): void {
|
||||
ss.set(LOCAL_NAME, setting)
|
||||
}
|
||||
|
||||
export function removeLocalState() {
|
||||
ss.remove(LOCAL_NAME)
|
||||
}
|
||||
22
src/store/modules/settings/index.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { SettingsState } from './helper'
|
||||
import { defaultSetting, getLocalState, removeLocalState, setLocalState } from './helper'
|
||||
|
||||
export const useSettingStore = defineStore('setting-store', {
|
||||
state: (): SettingsState => getLocalState(),
|
||||
actions: {
|
||||
updateSetting(settings: Partial<SettingsState>) {
|
||||
this.$state = { ...this.$state, ...settings }
|
||||
this.recordState()
|
||||
},
|
||||
|
||||
resetSetting() {
|
||||
this.$state = defaultSetting()
|
||||
removeLocalState()
|
||||
},
|
||||
|
||||
recordState() {
|
||||
setLocalState(this.$state)
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -3,3 +3,8 @@ body,
|
||||
#app {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
padding-bottom: constant(safe-area-inset-bottom);
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
}
|
||||
|
||||
@@ -123,7 +123,10 @@ html {
|
||||
}
|
||||
|
||||
code.hljs {
|
||||
padding: 3px 5px
|
||||
padding: 3px 5px;
|
||||
&::-webkit-scrollbar {
|
||||
height: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.hljs {
|
||||
|
||||
1
src/typings/chat.d.ts
vendored
@@ -18,6 +18,7 @@ declare namespace Chat {
|
||||
|
||||
interface ChatState {
|
||||
active: number | null
|
||||
usingContext: boolean;
|
||||
history: History[]
|
||||
chat: { uuid: number; data: Chat[] }[]
|
||||
}
|
||||
|
||||
3
src/typings/env.d.ts
vendored
@@ -2,6 +2,7 @@
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_GLOB_API_URL: string;
|
||||
readonly VITE_GLOB_API_TIMEOUT: string;
|
||||
readonly VITE_APP_API_BASE_URL: string;
|
||||
readonly VITE_GLOB_OPEN_LONG_REPLY: string;
|
||||
readonly VITE_GLOB_APP_PWA: string;
|
||||
}
|
||||
|
||||
18
src/utils/functions/debounce.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
type CallbackFunc<T extends unknown[]> = (...args: T) => void
|
||||
|
||||
export function debounce<T extends unknown[]>(
|
||||
func: CallbackFunc<T>,
|
||||
wait: number,
|
||||
): (...args: T) => void {
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
return (...args: T) => {
|
||||
const later = () => {
|
||||
clearTimeout(timeoutId)
|
||||
func(...args)
|
||||
}
|
||||
|
||||
clearTimeout(timeoutId)
|
||||
timeoutId = setTimeout(later, wait)
|
||||
}
|
||||
}
|
||||
7
src/utils/functions/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export function getCurrentDate() {
|
||||
const date = new Date()
|
||||
const day = date.getDate()
|
||||
const month = date.getMonth() + 1
|
||||
const year = date.getFullYear()
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import axios, { type AxiosResponse } from 'axios'
|
||||
import { useAuthStore } from '@/store'
|
||||
|
||||
const service = axios.create({
|
||||
baseURL: import.meta.env.VITE_GLOB_API_URL,
|
||||
@@ -6,6 +7,9 @@ const service = axios.create({
|
||||
|
||||
service.interceptors.request.use(
|
||||
(config) => {
|
||||
const token = useAuthStore().token
|
||||
if (token)
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
return config
|
||||
},
|
||||
(error) => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { AxiosProgressEvent, AxiosResponse, GenericAbortSignal } from 'axios'
|
||||
import request from './axios'
|
||||
import { useAuthStore } from '@/store'
|
||||
|
||||
export interface HttpOption {
|
||||
url: string
|
||||
@@ -22,9 +23,16 @@ function http<T = any>(
|
||||
{ url, data, method, headers, onDownloadProgress, signal, beforeRequest, afterRequest }: HttpOption,
|
||||
) {
|
||||
const successHandler = (res: AxiosResponse<Response<T>>) => {
|
||||
const authStore = useAuthStore()
|
||||
|
||||
if (res.data.status === 'Success' || typeof res.data === 'string')
|
||||
return res.data
|
||||
|
||||
if (res.data.status === 'Unauthorized') {
|
||||
authStore.removeToken()
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
return Promise.reject(res.data)
|
||||
}
|
||||
|
||||
|
||||
78
src/views/chat/components/Header/index.vue
Normal file
@@ -0,0 +1,78 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed, nextTick } from 'vue'
|
||||
import { HoverButton, SvgIcon } from '@/components/common'
|
||||
import { useAppStore, useChatStore } from '@/store'
|
||||
|
||||
interface Props {
|
||||
usingContext: boolean
|
||||
}
|
||||
|
||||
interface Emit {
|
||||
(ev: 'export'): void
|
||||
(ev: 'toggleUsingContext'): void
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
|
||||
const emit = defineEmits<Emit>()
|
||||
|
||||
const appStore = useAppStore()
|
||||
const chatStore = useChatStore()
|
||||
|
||||
const collapsed = computed(() => appStore.siderCollapsed)
|
||||
const currentChatHistory = computed(() => chatStore.getChatHistoryByCurrentActive)
|
||||
|
||||
function handleUpdateCollapsed() {
|
||||
appStore.setSiderCollapsed(!collapsed.value)
|
||||
}
|
||||
|
||||
function onScrollToTop() {
|
||||
const scrollRef = document.querySelector('#scrollRef')
|
||||
if (scrollRef)
|
||||
nextTick(() => scrollRef.scrollTop = 0)
|
||||
}
|
||||
|
||||
function handleExport() {
|
||||
emit('export')
|
||||
}
|
||||
|
||||
function toggleUsingContext() {
|
||||
emit('toggleUsingContext')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header
|
||||
class="sticky top-0 left-0 right-0 z-30 border-b dark:border-neutral-800 bg-white/80 dark:bg-black/20 backdrop-blur"
|
||||
>
|
||||
<div class="relative flex items-center justify-between min-w-0 overflow-hidden h-14">
|
||||
<div class="flex items-center">
|
||||
<button
|
||||
class="flex items-center justify-center w-11 h-11"
|
||||
@click="handleUpdateCollapsed"
|
||||
>
|
||||
<SvgIcon v-if="collapsed" class="text-2xl" icon="ri:align-justify" />
|
||||
<SvgIcon v-else class="text-2xl" icon="ri:align-right" />
|
||||
</button>
|
||||
</div>
|
||||
<h1
|
||||
class="flex-1 px-4 pr-6 overflow-hidden cursor-pointer select-none text-ellipsis whitespace-nowrap"
|
||||
@dblclick="onScrollToTop"
|
||||
>
|
||||
{{ currentChatHistory?.title ?? '' }}
|
||||
</h1>
|
||||
<div class="flex items-center space-x-2">
|
||||
<HoverButton @click="toggleUsingContext">
|
||||
<span class="text-xl" :class="{ 'text-[#4b9e5f]': usingContext, 'text-[#a8071a]': !usingContext }">
|
||||
<SvgIcon icon="ri:chat-history-line" />
|
||||
</span>
|
||||
</HoverButton>
|
||||
<HoverButton @click="handleExport">
|
||||
<span class="text-xl text-[#4f555e] dark:text-white">
|
||||
<SvgIcon icon="ri:download-2-line" />
|
||||
</span>
|
||||
</HoverButton>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
</template>
|
||||
@@ -1,9 +1,10 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import { marked } from 'marked'
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import mdKatex from '@traptitech/markdown-it-katex'
|
||||
import mila from 'markdown-it-link-attributes'
|
||||
import hljs from 'highlight.js'
|
||||
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||
import { encodeHTML } from '@/utils/format'
|
||||
import { t } from '@/locales'
|
||||
|
||||
interface Props {
|
||||
@@ -11,69 +12,67 @@ interface Props {
|
||||
error?: boolean
|
||||
text?: string
|
||||
loading?: boolean
|
||||
asRawText?: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const { isMobile } = useBasicLayout()
|
||||
|
||||
const renderer = new marked.Renderer()
|
||||
|
||||
const textRef = ref<HTMLElement>()
|
||||
|
||||
renderer.html = (html) => {
|
||||
return `<p>${encodeHTML(html)}</p>`
|
||||
}
|
||||
|
||||
renderer.code = (code, language) => {
|
||||
const validLang = !!(language && hljs.getLanguage(language))
|
||||
if (validLang) {
|
||||
const lang = language ?? ''
|
||||
return `<pre class="code-block-wrapper"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span><span class="code-block-header__copy">${t('chat.copyCode')}</span></div><code class="hljs code-block-body ${language}">${hljs.highlight(lang, code).value}</code></pre>`
|
||||
}
|
||||
return `<pre style="background: none">${hljs.highlightAuto(code).value}</pre>`
|
||||
}
|
||||
|
||||
marked.setOptions({
|
||||
renderer,
|
||||
highlight(code) {
|
||||
return hljs.highlightAuto(code).value
|
||||
const mdi = new MarkdownIt({
|
||||
linkify: true,
|
||||
highlight(code, language) {
|
||||
const validLang = !!(language && hljs.getLanguage(language))
|
||||
if (validLang) {
|
||||
const lang = language ?? ''
|
||||
return highlightBlock(hljs.highlight(code, { language: lang }).value, lang)
|
||||
}
|
||||
return highlightBlock(hljs.highlightAuto(code).value, '')
|
||||
},
|
||||
})
|
||||
|
||||
mdi.use(mila, { attrs: { target: '_blank', rel: 'noopener' } })
|
||||
mdi.use(mdKatex, { blockClass: 'katexmath-block rounded-md p-[10px]', errorColor: ' #cc0000' })
|
||||
|
||||
const wrapClass = computed(() => {
|
||||
return [
|
||||
'text-wrap',
|
||||
'min-w-[20px]',
|
||||
'rounded-md',
|
||||
isMobile.value ? 'p-2' : 'p-3',
|
||||
isMobile.value ? 'p-2' : 'px-3 py-2',
|
||||
props.inversion ? 'bg-[#d2f9d1]' : 'bg-[#f4f6f8]',
|
||||
props.inversion ? 'dark:bg-[#a1dc95]' : 'dark:bg-[#1e1e20]',
|
||||
props.inversion ? 'message-request' : 'message-reply',
|
||||
{ 'text-red-500': props.error },
|
||||
]
|
||||
})
|
||||
|
||||
const text = computed(() => {
|
||||
const value = props.text ?? ''
|
||||
if (!props.inversion)
|
||||
return marked(value)
|
||||
if (!props.asRawText)
|
||||
return mdi.render(value)
|
||||
return value
|
||||
})
|
||||
|
||||
function highlightBlock(str: string, lang?: string) {
|
||||
return `<pre class="code-block-wrapper"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span><span class="code-block-header__copy">${t('chat.copyCode')}</span></div><code class="hljs code-block-body ${lang}">${str}</code></pre>`
|
||||
}
|
||||
|
||||
defineExpose({ textRef })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="text-black" :class="wrapClass">
|
||||
<template v-if="loading">
|
||||
<span class="dark:text-white w-[4px] h-[20px] block animate-blink" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<div ref="textRef" class="leading-relaxed break-all">
|
||||
<div v-if="!inversion" class="markdown-body" v-html="text" />
|
||||
<div v-else class="whitespace-pre-wrap" v-text="text" />
|
||||
<div ref="textRef" class="leading-relaxed break-words">
|
||||
<div v-if="!inversion" class="flex items-end">
|
||||
<div v-if="!asRawText" class="w-full markdown-body" v-html="text" />
|
||||
<div v-else class="w-full whitespace-pre-wrap" v-text="text" />
|
||||
<span v-if="loading" class="dark:text-white w-[4px] h-[20px] block animate-blink" />
|
||||
</div>
|
||||
</template>
|
||||
<div v-else class="whitespace-pre-wrap" v-text="text" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang='ts'>
|
||||
import { ref } from 'vue'
|
||||
import { computed, ref } from 'vue'
|
||||
import { NDropdown } from 'naive-ui'
|
||||
import AvatarComponent from './Avatar.vue'
|
||||
import TextComponent from './Text.vue'
|
||||
@@ -7,6 +7,7 @@ import { SvgIcon } from '@/components/common'
|
||||
import { copyText } from '@/utils/format'
|
||||
import { useIconRender } from '@/hooks/useIconRender'
|
||||
import { t } from '@/locales'
|
||||
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||
|
||||
interface Props {
|
||||
dateTime?: string
|
||||
@@ -25,40 +26,66 @@ const props = defineProps<Props>()
|
||||
|
||||
const emit = defineEmits<Emit>()
|
||||
|
||||
const { isMobile } = useBasicLayout()
|
||||
|
||||
const { iconRender } = useIconRender()
|
||||
|
||||
const textRef = ref<HTMLElement>()
|
||||
|
||||
const options = [
|
||||
{
|
||||
label: t('chat.copy'),
|
||||
key: 'copyText',
|
||||
icon: iconRender({ icon: 'ri:file-copy-2-line' }),
|
||||
},
|
||||
{
|
||||
label: t('common.delete'),
|
||||
key: 'delete',
|
||||
icon: iconRender({ icon: 'ri:delete-bin-line' }),
|
||||
},
|
||||
]
|
||||
const asRawText = ref(props.inversion)
|
||||
|
||||
function handleSelect(key: 'copyRaw' | 'copyText' | 'delete') {
|
||||
const messageRef = ref<HTMLElement>()
|
||||
|
||||
const options = computed(() => {
|
||||
const common = [
|
||||
{
|
||||
label: t('chat.copy'),
|
||||
key: 'copyText',
|
||||
icon: iconRender({ icon: 'ri:file-copy-2-line' }),
|
||||
},
|
||||
{
|
||||
label: t('common.delete'),
|
||||
key: 'delete',
|
||||
icon: iconRender({ icon: 'ri:delete-bin-line' }),
|
||||
},
|
||||
]
|
||||
|
||||
if (!props.inversion) {
|
||||
common.unshift({
|
||||
label: asRawText.value ? t('chat.preview') : t('chat.showRawText'),
|
||||
key: 'toggleRenderType',
|
||||
icon: iconRender({ icon: asRawText.value ? 'ic:outline-code-off' : 'ic:outline-code' }),
|
||||
})
|
||||
}
|
||||
|
||||
return common
|
||||
})
|
||||
|
||||
function handleSelect(key: 'copyText' | 'delete' | 'toggleRenderType') {
|
||||
switch (key) {
|
||||
case 'copyText':
|
||||
copyText({ text: props.text ?? '' })
|
||||
return
|
||||
case 'toggleRenderType':
|
||||
asRawText.value = !asRawText.value
|
||||
return
|
||||
case 'delete':
|
||||
emit('delete')
|
||||
}
|
||||
}
|
||||
|
||||
function handleRegenerate() {
|
||||
messageRef.value?.scrollIntoView()
|
||||
emit('regenerate')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex w-full mb-6 overflow-hidden" :class="[{ 'flex-row-reverse': inversion }]">
|
||||
<div
|
||||
ref="messageRef"
|
||||
class="flex w-full mb-6 overflow-hidden"
|
||||
:class="[{ 'flex-row-reverse': inversion }]"
|
||||
>
|
||||
<div
|
||||
class="flex items-center justify-center flex-shrink-0 h-8 overflow-hidden rounded-full basis-8"
|
||||
:class="[inversion ? 'ml-2' : 'mr-2']"
|
||||
@@ -79,6 +106,7 @@ function handleRegenerate() {
|
||||
:error="error"
|
||||
:text="text"
|
||||
:loading="loading"
|
||||
:as-raw-text="asRawText"
|
||||
/>
|
||||
<div class="flex flex-col">
|
||||
<button
|
||||
@@ -88,7 +116,12 @@ function handleRegenerate() {
|
||||
>
|
||||
<SvgIcon icon="ri:restart-line" />
|
||||
</button>
|
||||
<NDropdown :placement="!inversion ? 'right' : 'left'" :options="options" @select="handleSelect">
|
||||
<NDropdown
|
||||
:trigger="isMobile ? 'click' : 'hover'"
|
||||
:placement="!inversion ? 'right' : 'left'"
|
||||
:options="options"
|
||||
@select="handleSelect"
|
||||
>
|
||||
<button class="transition text-neutral-300 hover:text-neutral-800 dark:hover:text-neutral-200">
|
||||
<SvgIcon icon="ri:more-2-fill" />
|
||||
</button>
|
||||
|
||||
@@ -45,20 +45,29 @@
|
||||
align-items: center;
|
||||
color: #b3b3b3;
|
||||
|
||||
&__copy{
|
||||
&__copy {
|
||||
cursor: pointer;
|
||||
margin-left: 0.5rem;
|
||||
user-select: none;
|
||||
|
||||
&:hover {
|
||||
color: #65a665;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
html.dark {
|
||||
|
||||
.message-reply {
|
||||
.whitespace-pre-wrap {
|
||||
white-space: pre-wrap;
|
||||
color: var(--n-text-color);
|
||||
}
|
||||
}
|
||||
|
||||
.highlight pre,
|
||||
pre {
|
||||
background-color: #282c34;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { onMounted } from 'vue'
|
||||
import { onMounted, onUpdated } from 'vue'
|
||||
import { copyText } from '@/utils/format'
|
||||
|
||||
export function useCopyCode() {
|
||||
function copyCodeBlock() {
|
||||
@@ -8,11 +9,16 @@ export function useCopyCode() {
|
||||
const codeBlock = wrapper.querySelector('.code-block-body')
|
||||
if (copyBtn && codeBlock) {
|
||||
copyBtn.addEventListener('click', () => {
|
||||
navigator.clipboard.writeText(codeBlock.textContent ?? '')
|
||||
if (navigator.clipboard?.writeText)
|
||||
navigator.clipboard.writeText(codeBlock.textContent ?? '')
|
||||
else
|
||||
copyText({ text: codeBlock.textContent ?? '', origin: true })
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(() => copyCodeBlock())
|
||||
|
||||
onUpdated(() => copyCodeBlock())
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ interface ScrollReturn {
|
||||
scrollRef: Ref<ScrollElement>
|
||||
scrollToBottom: () => Promise<void>
|
||||
scrollToTop: () => Promise<void>
|
||||
scrollToBottomIfAtBottom: () => Promise<void>
|
||||
}
|
||||
|
||||
export function useScroll(): ScrollReturn {
|
||||
@@ -24,9 +25,20 @@ export function useScroll(): ScrollReturn {
|
||||
scrollRef.value.scrollTop = 0
|
||||
}
|
||||
|
||||
const scrollToBottomIfAtBottom = async () => {
|
||||
await nextTick()
|
||||
if (scrollRef.value) {
|
||||
const threshold = 100 // 阈值,表示滚动条到底部的距离阈值
|
||||
const distanceToBottom = scrollRef.value.scrollHeight - scrollRef.value.scrollTop - scrollRef.value.clientHeight
|
||||
if (distanceToBottom <= threshold)
|
||||
scrollRef.value.scrollTop = scrollRef.value.scrollHeight
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
scrollRef,
|
||||
scrollToBottom,
|
||||
scrollToTop,
|
||||
scrollToBottomIfAtBottom,
|
||||
}
|
||||
}
|
||||
|
||||
23
src/views/chat/hooks/useUsingContext.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { computed } from 'vue'
|
||||
import { useMessage } from 'naive-ui'
|
||||
import { t } from '@/locales'
|
||||
import { useChatStore } from '@/store'
|
||||
|
||||
export function useUsingContext() {
|
||||
const ms = useMessage()
|
||||
const chatStore = useChatStore()
|
||||
const usingContext = computed<boolean>(() => chatStore.usingContext)
|
||||
|
||||
function toggleUsingContext() {
|
||||
chatStore.setUsingContext(!usingContext.value)
|
||||
if (usingContext.value)
|
||||
ms.success(t('chat.turnOnContext'))
|
||||
else
|
||||
ms.warning(t('chat.turnOffContext'))
|
||||
}
|
||||
|
||||
return {
|
||||
usingContext,
|
||||
toggleUsingContext,
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,38 @@
|
||||
<script setup lang='ts'>
|
||||
import type { Ref } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { NButton, NInput, useDialog } from 'naive-ui'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { NAutoComplete, NButton, NInput, useDialog, useMessage } from 'naive-ui'
|
||||
import html2canvas from 'html2canvas'
|
||||
import { Message } from './components'
|
||||
import { useScroll } from './hooks/useScroll'
|
||||
import { useChat } from './hooks/useChat'
|
||||
import { useCopyCode } from './hooks/useCopyCode'
|
||||
import { useUsingContext } from './hooks/useUsingContext'
|
||||
import HeaderComponent from './components/Header/index.vue'
|
||||
import { HoverButton, SvgIcon } from '@/components/common'
|
||||
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||
import { useChatStore } from '@/store'
|
||||
import { useChatStore, usePromptStore } from '@/store'
|
||||
import { fetchChatAPIProcess } from '@/api'
|
||||
import { t } from '@/locales'
|
||||
|
||||
let controller = new AbortController()
|
||||
|
||||
const openLongReply = import.meta.env.VITE_GLOB_OPEN_LONG_REPLY === 'true'
|
||||
|
||||
const route = useRoute()
|
||||
const dialog = useDialog()
|
||||
const ms = useMessage()
|
||||
|
||||
const chatStore = useChatStore()
|
||||
|
||||
useCopyCode()
|
||||
|
||||
const { isMobile } = useBasicLayout()
|
||||
const { addChat, updateChat, updateChatSome, getChatByUuidAndIndex } = useChat()
|
||||
const { scrollRef, scrollToBottom } = useScroll()
|
||||
const { scrollRef, scrollToBottom, scrollToBottomIfAtBottom } = useScroll()
|
||||
const { usingContext, toggleUsingContext } = useUsingContext()
|
||||
|
||||
const { uuid } = route.params as { uuid: string }
|
||||
|
||||
@@ -31,13 +41,26 @@ const conversationList = computed(() => dataSources.value.filter(item => (!item.
|
||||
|
||||
const prompt = ref<string>('')
|
||||
const loading = ref<boolean>(false)
|
||||
const inputRef = ref<Ref | null>(null)
|
||||
|
||||
// 添加PromptStore
|
||||
const promptStore = usePromptStore()
|
||||
|
||||
// 使用storeToRefs,保证store修改后,联想部分能够重新渲染
|
||||
const { promptList: promptTemplate } = storeToRefs<any>(promptStore)
|
||||
|
||||
// 未知原因刷新页面,loading 状态不会重置,手动重置
|
||||
dataSources.value.forEach((item, index) => {
|
||||
if (item.loading)
|
||||
updateChatSome(+uuid, index, { loading: false })
|
||||
})
|
||||
|
||||
function handleSubmit() {
|
||||
onConversation()
|
||||
}
|
||||
|
||||
async function onConversation() {
|
||||
const message = prompt.value
|
||||
let message = prompt.value
|
||||
|
||||
if (loading.value)
|
||||
return
|
||||
@@ -66,7 +89,7 @@ async function onConversation() {
|
||||
let options: Chat.ConversationRequest = {}
|
||||
const lastContext = conversationList.value[conversationList.value.length - 1]?.conversationOptions
|
||||
|
||||
if (lastContext)
|
||||
if (lastContext && usingContext.value)
|
||||
options = { ...lastContext }
|
||||
|
||||
addChat(
|
||||
@@ -84,40 +107,54 @@ async function onConversation() {
|
||||
scrollToBottom()
|
||||
|
||||
try {
|
||||
await fetchChatAPIProcess<Chat.ConversationResponse>({
|
||||
prompt: message,
|
||||
options,
|
||||
signal: controller.signal,
|
||||
onDownloadProgress: ({ event }) => {
|
||||
const xhr = event.target
|
||||
const { responseText } = xhr
|
||||
// Always process the final line
|
||||
const lastIndex = responseText.lastIndexOf('\n')
|
||||
let chunk = responseText
|
||||
if (lastIndex !== -1)
|
||||
chunk = responseText.substring(lastIndex)
|
||||
try {
|
||||
const data = JSON.parse(chunk)
|
||||
updateChat(
|
||||
+uuid,
|
||||
dataSources.value.length - 1,
|
||||
{
|
||||
dateTime: new Date().toLocaleString(),
|
||||
text: data.text ?? '',
|
||||
inversion: false,
|
||||
error: false,
|
||||
loading: false,
|
||||
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
|
||||
requestOptions: { prompt: message, options: { ...options } },
|
||||
},
|
||||
)
|
||||
scrollToBottom()
|
||||
}
|
||||
catch (error) {
|
||||
//
|
||||
}
|
||||
},
|
||||
})
|
||||
let lastText = ''
|
||||
const fetchChatAPIOnce = async () => {
|
||||
await fetchChatAPIProcess<Chat.ConversationResponse>({
|
||||
prompt: message,
|
||||
options,
|
||||
signal: controller.signal,
|
||||
onDownloadProgress: ({ event }) => {
|
||||
const xhr = event.target
|
||||
const { responseText } = xhr
|
||||
// Always process the final line
|
||||
const lastIndex = responseText.lastIndexOf('\n', responseText.length - 2)
|
||||
let chunk = responseText
|
||||
if (lastIndex !== -1)
|
||||
chunk = responseText.substring(lastIndex)
|
||||
try {
|
||||
const data = JSON.parse(chunk)
|
||||
updateChat(
|
||||
+uuid,
|
||||
dataSources.value.length - 1,
|
||||
{
|
||||
dateTime: new Date().toLocaleString(),
|
||||
text: lastText + (data.text ?? ''),
|
||||
inversion: false,
|
||||
error: false,
|
||||
loading: true,
|
||||
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
|
||||
requestOptions: { prompt: message, options: { ...options } },
|
||||
},
|
||||
)
|
||||
|
||||
if (openLongReply && data.detail.choices[0].finish_reason === 'length') {
|
||||
options.parentMessageId = data.id
|
||||
lastText = data.text
|
||||
message = ''
|
||||
return fetchChatAPIOnce()
|
||||
}
|
||||
|
||||
scrollToBottomIfAtBottom()
|
||||
}
|
||||
catch (error) {
|
||||
//
|
||||
}
|
||||
},
|
||||
})
|
||||
updateChatSome(+uuid, dataSources.value.length - 1, { loading: false })
|
||||
}
|
||||
|
||||
await fetchChatAPIOnce()
|
||||
}
|
||||
catch (error: any) {
|
||||
const errorMessage = error?.message ?? t('common.wrong')
|
||||
@@ -130,7 +167,7 @@ async function onConversation() {
|
||||
loading: false,
|
||||
},
|
||||
)
|
||||
scrollToBottom()
|
||||
scrollToBottomIfAtBottom()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -162,7 +199,7 @@ async function onConversation() {
|
||||
requestOptions: { prompt: message, options: { ...options } },
|
||||
},
|
||||
)
|
||||
scrollToBottom()
|
||||
scrollToBottomIfAtBottom()
|
||||
}
|
||||
finally {
|
||||
loading.value = false
|
||||
@@ -177,7 +214,7 @@ async function onRegenerate(index: number) {
|
||||
|
||||
const { requestOptions } = dataSources.value[index]
|
||||
|
||||
const message = requestOptions?.prompt ?? ''
|
||||
let message = requestOptions?.prompt ?? ''
|
||||
|
||||
let options: Chat.ConversationRequest = {}
|
||||
|
||||
@@ -201,39 +238,51 @@ async function onRegenerate(index: number) {
|
||||
)
|
||||
|
||||
try {
|
||||
await fetchChatAPIProcess<Chat.ConversationResponse>({
|
||||
prompt: message,
|
||||
options,
|
||||
signal: controller.signal,
|
||||
onDownloadProgress: ({ event }) => {
|
||||
const xhr = event.target
|
||||
const { responseText } = xhr
|
||||
// Always process the final line
|
||||
const lastIndex = responseText.lastIndexOf('\n')
|
||||
let chunk = responseText
|
||||
if (lastIndex !== -1)
|
||||
chunk = responseText.substring(lastIndex)
|
||||
try {
|
||||
const data = JSON.parse(chunk)
|
||||
updateChat(
|
||||
+uuid,
|
||||
index,
|
||||
{
|
||||
dateTime: new Date().toLocaleString(),
|
||||
text: data.text ?? '',
|
||||
inversion: false,
|
||||
error: false,
|
||||
loading: false,
|
||||
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
|
||||
requestOptions: { prompt: message, ...options },
|
||||
},
|
||||
)
|
||||
}
|
||||
catch (error) {
|
||||
//
|
||||
}
|
||||
},
|
||||
})
|
||||
let lastText = ''
|
||||
const fetchChatAPIOnce = async () => {
|
||||
await fetchChatAPIProcess<Chat.ConversationResponse>({
|
||||
prompt: message,
|
||||
options,
|
||||
signal: controller.signal,
|
||||
onDownloadProgress: ({ event }) => {
|
||||
const xhr = event.target
|
||||
const { responseText } = xhr
|
||||
// Always process the final line
|
||||
const lastIndex = responseText.lastIndexOf('\n', responseText.length - 2)
|
||||
let chunk = responseText
|
||||
if (lastIndex !== -1)
|
||||
chunk = responseText.substring(lastIndex)
|
||||
try {
|
||||
const data = JSON.parse(chunk)
|
||||
updateChat(
|
||||
+uuid,
|
||||
index,
|
||||
{
|
||||
dateTime: new Date().toLocaleString(),
|
||||
text: lastText + (data.text ?? ''),
|
||||
inversion: false,
|
||||
error: false,
|
||||
loading: true,
|
||||
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
|
||||
requestOptions: { prompt: message, ...options },
|
||||
},
|
||||
)
|
||||
|
||||
if (openLongReply && data.detail.choices[0].finish_reason === 'length') {
|
||||
options.parentMessageId = data.id
|
||||
lastText = data.text
|
||||
message = ''
|
||||
return fetchChatAPIOnce()
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
//
|
||||
}
|
||||
},
|
||||
})
|
||||
updateChatSome(+uuid, index, { loading: false })
|
||||
}
|
||||
await fetchChatAPIOnce()
|
||||
}
|
||||
catch (error: any) {
|
||||
if (error.message === 'canceled') {
|
||||
@@ -268,6 +317,48 @@ async function onRegenerate(index: number) {
|
||||
}
|
||||
}
|
||||
|
||||
function handleExport() {
|
||||
if (loading.value)
|
||||
return
|
||||
|
||||
const d = dialog.warning({
|
||||
title: t('chat.exportImage'),
|
||||
content: t('chat.exportImageConfirm'),
|
||||
positiveText: t('common.yes'),
|
||||
negativeText: t('common.no'),
|
||||
onPositiveClick: async () => {
|
||||
try {
|
||||
d.loading = true
|
||||
const ele = document.getElementById('image-wrapper')
|
||||
const canvas = await html2canvas(ele as HTMLDivElement, {
|
||||
useCORS: true,
|
||||
})
|
||||
const imgUrl = canvas.toDataURL('image/png')
|
||||
const tempLink = document.createElement('a')
|
||||
tempLink.style.display = 'none'
|
||||
tempLink.href = imgUrl
|
||||
tempLink.setAttribute('download', 'chat-shot.png')
|
||||
if (typeof tempLink.download === 'undefined')
|
||||
tempLink.setAttribute('target', '_blank')
|
||||
|
||||
document.body.appendChild(tempLink)
|
||||
tempLink.click()
|
||||
document.body.removeChild(tempLink)
|
||||
window.URL.revokeObjectURL(imgUrl)
|
||||
d.loading = false
|
||||
ms.success(t('chat.exportSuccess'))
|
||||
Promise.resolve()
|
||||
}
|
||||
catch (error: any) {
|
||||
ms.error(t('chat.exportFailed'))
|
||||
}
|
||||
finally {
|
||||
d.loading = false
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function handleDelete(index: number) {
|
||||
if (loading.value)
|
||||
return
|
||||
@@ -305,6 +396,12 @@ function handleEnter(event: KeyboardEvent) {
|
||||
handleSubmit()
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (event.key === 'Enter' && event.ctrlKey) {
|
||||
event.preventDefault()
|
||||
handleSubmit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleStop() {
|
||||
@@ -314,6 +411,32 @@ function handleStop() {
|
||||
}
|
||||
}
|
||||
|
||||
// 可优化部分
|
||||
// 搜索选项计算,这里使用value作为索引项,所以当出现重复value时渲染异常(多项同时出现选中效果)
|
||||
// 理想状态下其实应该是key作为索引项,但官方的renderOption会出现问题,所以就需要value反renderLabel实现
|
||||
const searchOptions = computed(() => {
|
||||
if (prompt.value.startsWith('/')) {
|
||||
return promptTemplate.value.filter((item: { key: string }) => item.key.toLowerCase().includes(prompt.value.substring(1).toLowerCase())).map((obj: { value: any }) => {
|
||||
return {
|
||||
label: obj.value,
|
||||
value: obj.value,
|
||||
}
|
||||
})
|
||||
}
|
||||
else {
|
||||
return []
|
||||
}
|
||||
})
|
||||
|
||||
// value反渲染key
|
||||
const renderOption = (option: { label: string }) => {
|
||||
for (const i of promptTemplate.value) {
|
||||
if (i.value === option.label)
|
||||
return [i.key]
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
const placeholder = computed(() => {
|
||||
if (isMobile.value)
|
||||
return t('chat.placeholderMobile')
|
||||
@@ -324,22 +447,17 @@ const buttonDisabled = computed(() => {
|
||||
return loading.value || !prompt.value || prompt.value.trim() === ''
|
||||
})
|
||||
|
||||
const wrapClass = computed(() => {
|
||||
if (isMobile.value)
|
||||
return ['pt-14', 'pb-16']
|
||||
|
||||
return []
|
||||
})
|
||||
|
||||
const footerClass = computed(() => {
|
||||
let classes = ['p-4']
|
||||
if (isMobile.value)
|
||||
classes = ['p-2', 'pr-4', 'fixed', 'bottom-4', 'left-0', 'right-0', 'z-30', 'h-14', 'overflow-hidden']
|
||||
classes = ['sticky', 'left-0', 'bottom-0', 'right-0', 'p-2', 'pr-3', 'overflow-hidden']
|
||||
return classes
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
scrollToBottom()
|
||||
if (inputRef.value && !isMobile.value)
|
||||
inputRef.value?.focus()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
@@ -349,66 +467,93 @@ onUnmounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col h-full" :class="wrapClass">
|
||||
<div class="flex flex-col w-full h-full">
|
||||
<HeaderComponent
|
||||
v-if="isMobile"
|
||||
:using-context="usingContext"
|
||||
@export="handleExport"
|
||||
@toggle-using-context="toggleUsingContext"
|
||||
/>
|
||||
<main class="flex-1 overflow-hidden">
|
||||
<div
|
||||
id="scrollRef"
|
||||
ref="scrollRef"
|
||||
class="h-full overflow-hidden overflow-y-auto"
|
||||
:class="[isMobile ? 'p-2' : 'p-4']"
|
||||
>
|
||||
<template v-if="!dataSources.length">
|
||||
<div class="flex items-center justify-center mt-4 text-center text-neutral-300">
|
||||
<SvgIcon icon="ri:bubble-chart-fill" class="mr-2 text-3xl" />
|
||||
<span>Aha~</span>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div>
|
||||
<Message
|
||||
v-for="(item, index) of dataSources"
|
||||
:key="index"
|
||||
:date-time="item.dateTime"
|
||||
:text="item.text"
|
||||
:inversion="item.inversion"
|
||||
:error="item.error"
|
||||
:loading="item.loading"
|
||||
@regenerate="onRegenerate(index)"
|
||||
@delete="handleDelete(index)"
|
||||
/>
|
||||
<div class="sticky bottom-0 left-0 flex justify-center">
|
||||
<NButton v-if="loading" type="warning" @click="handleStop">
|
||||
<template #icon>
|
||||
<SvgIcon icon="ri:stop-circle-line" />
|
||||
</template>
|
||||
Stop Responding
|
||||
</NButton>
|
||||
<div id="scrollRef" ref="scrollRef" class="h-full overflow-hidden overflow-y-auto">
|
||||
<div
|
||||
id="image-wrapper"
|
||||
class="w-full max-w-screen-xl m-auto dark:bg-[#101014]"
|
||||
:class="[isMobile ? 'p-2' : 'p-4']"
|
||||
>
|
||||
<template v-if="!dataSources.length">
|
||||
<div class="flex items-center justify-center mt-4 text-center text-neutral-300">
|
||||
<SvgIcon icon="ri:bubble-chart-fill" class="mr-2 text-3xl" />
|
||||
<span>Aha~</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div>
|
||||
<Message
|
||||
v-for="(item, index) of dataSources"
|
||||
:key="index"
|
||||
:date-time="item.dateTime"
|
||||
:text="item.text"
|
||||
:inversion="item.inversion"
|
||||
:error="item.error"
|
||||
:loading="item.loading"
|
||||
@regenerate="onRegenerate(index)"
|
||||
@delete="handleDelete(index)"
|
||||
/>
|
||||
<div class="sticky bottom-0 left-0 flex justify-center">
|
||||
<NButton v-if="loading" type="warning" @click="handleStop">
|
||||
<template #icon>
|
||||
<SvgIcon icon="ri:stop-circle-line" />
|
||||
</template>
|
||||
Stop Responding
|
||||
</NButton>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<footer :class="footerClass">
|
||||
<div class="flex items-center justify-between space-x-2">
|
||||
<HoverButton @click="handleClear">
|
||||
<span class="text-xl text-[#4f555e] dark:text-white">
|
||||
<SvgIcon icon="ri:delete-bin-line" />
|
||||
</span>
|
||||
</HoverButton>
|
||||
<NInput
|
||||
v-model:value="prompt"
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 1, maxRows: 2 }"
|
||||
:placeholder="placeholder"
|
||||
@keypress="handleEnter"
|
||||
/>
|
||||
<NButton type="primary" :disabled="buttonDisabled" @click="handleSubmit">
|
||||
<template #icon>
|
||||
<span class="dark:text-black">
|
||||
<SvgIcon icon="ri:send-plane-fill" />
|
||||
<div class="w-full max-w-screen-xl m-auto">
|
||||
<div class="flex items-center justify-between space-x-2">
|
||||
<HoverButton @click="handleClear">
|
||||
<span class="text-xl text-[#4f555e] dark:text-white">
|
||||
<SvgIcon icon="ri:delete-bin-line" />
|
||||
</span>
|
||||
</template>
|
||||
</NButton>
|
||||
</HoverButton>
|
||||
<HoverButton v-if="!isMobile" @click="handleExport">
|
||||
<span class="text-xl text-[#4f555e] dark:text-white">
|
||||
<SvgIcon icon="ri:download-2-line" />
|
||||
</span>
|
||||
</HoverButton>
|
||||
<HoverButton v-if="!isMobile" @click="toggleUsingContext">
|
||||
<span class="text-xl" :class="{ 'text-[#4b9e5f]': usingContext, 'text-[#a8071a]': !usingContext }">
|
||||
<SvgIcon icon="ri:chat-history-line" />
|
||||
</span>
|
||||
</HoverButton>
|
||||
<NAutoComplete v-model:value="prompt" :options="searchOptions" :render-label="renderOption">
|
||||
<template #default="{ handleInput, handleBlur, handleFocus }">
|
||||
<NInput
|
||||
ref="inputRef"
|
||||
v-model:value="prompt"
|
||||
type="textarea"
|
||||
:placeholder="placeholder"
|
||||
:autosize="{ minRows: 1, maxRows: isMobile ? 4 : 8 }"
|
||||
@input="handleInput"
|
||||
@focus="handleFocus"
|
||||
@blur="handleBlur"
|
||||
@keypress="handleEnter"
|
||||
/>
|
||||
</template>
|
||||
</NAutoComplete>
|
||||
<NButton type="primary" :disabled="buttonDisabled" @click="handleSubmit">
|
||||
<template #icon>
|
||||
<span class="dark:text-black">
|
||||
<SvgIcon icon="ri:send-plane-fill" />
|
||||
</span>
|
||||
</template>
|
||||
</NButton>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
@@ -3,13 +3,14 @@ import { computed } from 'vue'
|
||||
import { NLayout, NLayoutContent } from 'naive-ui'
|
||||
import { useRouter } from 'vue-router'
|
||||
import Sider from './sider/index.vue'
|
||||
import Header from './header/index.vue'
|
||||
import Permission from './Permission.vue'
|
||||
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||
import { useAppStore, useChatStore } from '@/store'
|
||||
import { useAppStore, useAuthStore, useChatStore } from '@/store'
|
||||
|
||||
const router = useRouter()
|
||||
const appStore = useAppStore()
|
||||
const chatStore = useChatStore()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
router.replace({ name: 'Chat', params: { uuid: chatStore.active } })
|
||||
|
||||
@@ -17,6 +18,8 @@ const { isMobile } = useBasicLayout()
|
||||
|
||||
const collapsed = computed(() => appStore.siderCollapsed)
|
||||
|
||||
const needPermission = computed(() => !!authStore.session?.auth && !authStore.token)
|
||||
|
||||
const getMobileClass = computed(() => {
|
||||
if (isMobile.value)
|
||||
return ['rounded-none', 'shadow-none']
|
||||
@@ -36,7 +39,6 @@ const getContainerClass = computed(() => {
|
||||
<div class="h-full overflow-hidden" :class="getMobileClass">
|
||||
<NLayout class="z-40 transition" :class="getContainerClass" has-sider>
|
||||
<Sider />
|
||||
<Header v-if="isMobile" />
|
||||
<NLayoutContent class="h-full">
|
||||
<RouterView v-slot="{ Component, route }">
|
||||
<component :is="Component" :key="route.fullPath" />
|
||||
@@ -44,5 +46,6 @@ const getContainerClass = computed(() => {
|
||||
</NLayoutContent>
|
||||
</NLayout>
|
||||
</div>
|
||||
<Permission :visible="needPermission" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
80
src/views/chat/layout/Permission.vue
Normal file
@@ -0,0 +1,80 @@
|
||||
<script setup lang='ts'>
|
||||
import { computed, ref } from 'vue'
|
||||
import { NButton, NInput, NModal, useMessage } from 'naive-ui'
|
||||
import { fetchVerify } from '@/api'
|
||||
import { useAuthStore } from '@/store'
|
||||
import Icon403 from '@/icons/403.vue'
|
||||
|
||||
interface Props {
|
||||
visible: boolean
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const ms = useMessage()
|
||||
|
||||
const loading = ref(false)
|
||||
const token = ref('')
|
||||
|
||||
const disabled = computed(() => !token.value.trim() || loading.value)
|
||||
|
||||
async function handleVerify() {
|
||||
const secretKey = token.value.trim()
|
||||
|
||||
if (!secretKey)
|
||||
return
|
||||
|
||||
try {
|
||||
loading.value = true
|
||||
await fetchVerify(secretKey)
|
||||
authStore.setToken(secretKey)
|
||||
ms.success('success')
|
||||
window.location.reload()
|
||||
}
|
||||
catch (error: any) {
|
||||
ms.error(error.message ?? 'error')
|
||||
authStore.removeToken()
|
||||
token.value = ''
|
||||
}
|
||||
finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handlePress(event: KeyboardEvent) {
|
||||
if (event.key === 'Enter' && !event.shiftKey) {
|
||||
event.preventDefault()
|
||||
handleVerify()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NModal :show="visible" style="width: 90%; max-width: 640px">
|
||||
<div class="p-10 bg-white rounded dark:bg-slate-800">
|
||||
<div class="space-y-4">
|
||||
<header class="space-y-2">
|
||||
<h2 class="text-2xl font-bold text-center text-slate-800 dark:text-neutral-200">
|
||||
403
|
||||
</h2>
|
||||
<p class="text-base text-center text-slate-500 dark:text-slate-500">
|
||||
{{ $t('common.unauthorizedTips') }}
|
||||
</p>
|
||||
<Icon403 class="w-[200px] m-auto" />
|
||||
</header>
|
||||
<NInput v-model:value="token" type="password" placeholder="" @keypress="handlePress" />
|
||||
<NButton
|
||||
block
|
||||
type="primary"
|
||||
:disabled="disabled"
|
||||
:loading="loading"
|
||||
@click="handleVerify"
|
||||
>
|
||||
{{ $t('common.verify') }}
|
||||
</NButton>
|
||||
</div>
|
||||
</div>
|
||||
</NModal>
|
||||
</template>
|
||||
@@ -1,55 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed, nextTick } from 'vue'
|
||||
import { SvgIcon } from '@/components/common'
|
||||
import { useAppStore, useChatStore } from '@/store'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const chatStore = useChatStore()
|
||||
|
||||
const collapsed = computed(() => appStore.siderCollapsed)
|
||||
const currentChatHistory = computed(() => chatStore.getChatHistoryByCurrentActive)
|
||||
|
||||
function handleUpdateCollapsed() {
|
||||
appStore.setSiderCollapsed(!collapsed.value)
|
||||
}
|
||||
|
||||
function onScrollToTop() {
|
||||
const scrollRef = document.querySelector('#scrollRef')
|
||||
if (scrollRef)
|
||||
nextTick(() => scrollRef.scrollTop = 0)
|
||||
}
|
||||
|
||||
function onScrollToBottom() {
|
||||
const scrollRef = document.querySelector('#scrollRef')
|
||||
if (scrollRef)
|
||||
nextTick(() => scrollRef.scrollTop = scrollRef.scrollHeight)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header
|
||||
class="fixed top-0 left-0 right-0 z-30 border-b dark:border-neutral-800 bg-white/80 dark:bg-black/20 backdrop-blur"
|
||||
>
|
||||
<div class="relative flex items-center justify-between h-14">
|
||||
<button
|
||||
class="flex items-center justify-center w-11 h-11"
|
||||
@click="handleUpdateCollapsed"
|
||||
>
|
||||
<SvgIcon v-if="collapsed" class="text-2xl" icon="ri:align-justify" />
|
||||
<SvgIcon v-else class="text-2xl" icon="ri:align-right" />
|
||||
</button>
|
||||
<h1
|
||||
class="flex-1 px-4 overflow-hidden text-center cursor-pointer select-none text-ellipsis whitespace-nowrap"
|
||||
@dblclick="onScrollToTop"
|
||||
>
|
||||
{{ currentChatHistory?.title ?? '' }}
|
||||
</h1>
|
||||
<button
|
||||
class="flex items-center justify-center w-11 h-11"
|
||||
@click="onScrollToBottom"
|
||||
>
|
||||
<SvgIcon class="text-2xl" icon="ri:arrow-down-s-line" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
</template>
|
||||
@@ -9,9 +9,11 @@ const show = ref(false)
|
||||
|
||||
<template>
|
||||
<footer class="flex items-center justify-between min-w-0 p-4 overflow-hidden border-t dark:border-neutral-800">
|
||||
<UserAvatar />
|
||||
<div class="flex-1 flex-shrink-0 overflow-hidden">
|
||||
<UserAvatar />
|
||||
</div>
|
||||
|
||||
<HoverButton :tooltip="$t('setting.setting')" @click="show = true">
|
||||
<HoverButton @click="show = true">
|
||||
<span class="text-xl text-[#4f555e] dark:text-white">
|
||||
<SvgIcon icon="ri:settings-4-line" />
|
||||
</span>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { NInput, NPopconfirm, NScrollbar } from 'naive-ui'
|
||||
import { SvgIcon } from '@/components/common'
|
||||
import { useAppStore, useChatStore } from '@/store'
|
||||
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||
import { debounce } from '@/utils/functions/debounce'
|
||||
|
||||
const { isMobile } = useBasicLayout()
|
||||
|
||||
@@ -16,6 +17,8 @@ async function handleSelect({ uuid }: Chat.History) {
|
||||
if (isActive(uuid))
|
||||
return
|
||||
|
||||
if (chatStore.active)
|
||||
chatStore.updateHistory(chatStore.active, { isEdit: false })
|
||||
await chatStore.setActive(uuid)
|
||||
|
||||
if (isMobile.value)
|
||||
@@ -30,8 +33,12 @@ function handleEdit({ uuid }: Chat.History, isEdit: boolean, event?: MouseEvent)
|
||||
function handleDelete(index: number, event?: MouseEvent | TouchEvent) {
|
||||
event?.stopPropagation()
|
||||
chatStore.deleteHistory(index)
|
||||
if (isMobile.value)
|
||||
appStore.setSiderCollapsed(true)
|
||||
}
|
||||
|
||||
const handleDeleteDebounce = debounce(handleDelete, 600)
|
||||
|
||||
function handleEnter({ uuid }: Chat.History, isEdit: boolean, event: KeyboardEvent) {
|
||||
event?.stopPropagation()
|
||||
if (event.key === 'Enter')
|
||||
@@ -65,8 +72,7 @@ function isActive(uuid: number) {
|
||||
<div class="relative flex-1 overflow-hidden break-all text-ellipsis whitespace-nowrap">
|
||||
<NInput
|
||||
v-if="item.isEdit"
|
||||
v-model:value="item.title"
|
||||
size="tiny"
|
||||
v-model:value="item.title" size="tiny"
|
||||
@keypress="handleEnter(item, false, $event)"
|
||||
/>
|
||||
<span v-else>{{ item.title }}</span>
|
||||
@@ -81,7 +87,7 @@ function isActive(uuid: number) {
|
||||
<button class="p-1">
|
||||
<SvgIcon icon="ri:edit-line" @click="handleEdit(item, true, $event)" />
|
||||
</button>
|
||||
<NPopconfirm placement="bottom" @positive-click="handleDelete(index, $event)">
|
||||
<NPopconfirm placement="bottom" @positive-click="handleDeleteDebounce(index, $event)">
|
||||
<template #trigger>
|
||||
<button class="p-1">
|
||||
<SvgIcon icon="ri:delete-bin-line" />
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
<script setup lang='ts'>
|
||||
import type { CSSProperties } from 'vue'
|
||||
import { computed, watch } from 'vue'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { NButton, NLayoutSider } from 'naive-ui'
|
||||
import List from './List.vue'
|
||||
import Footer from './Footer.vue'
|
||||
import { useAppStore, useChatStore } from '@/store'
|
||||
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||
import { PromptStore } from '@/components/common'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const chatStore = useChatStore()
|
||||
|
||||
const { isMobile } = useBasicLayout()
|
||||
const show = ref(false)
|
||||
|
||||
const collapsed = computed(() => appStore.siderCollapsed)
|
||||
|
||||
function handleAdd() {
|
||||
chatStore.addHistory({ title: 'New Chat', uuid: Date.now(), isEdit: false })
|
||||
if (isMobile.value)
|
||||
appStore.setSiderCollapsed(true)
|
||||
}
|
||||
|
||||
function handleUpdateCollapsed() {
|
||||
@@ -32,6 +36,15 @@ const getMobileClass = computed<CSSProperties>(() => {
|
||||
return {}
|
||||
})
|
||||
|
||||
const mobileSafeArea = computed(() => {
|
||||
if (isMobile.value) {
|
||||
return {
|
||||
paddingBottom: 'env(safe-area-inset-bottom)',
|
||||
}
|
||||
}
|
||||
return {}
|
||||
})
|
||||
|
||||
watch(
|
||||
isMobile,
|
||||
(val) => {
|
||||
@@ -56,16 +69,21 @@ watch(
|
||||
:style="getMobileClass"
|
||||
@update-collapsed="handleUpdateCollapsed"
|
||||
>
|
||||
<div class="flex flex-col h-full">
|
||||
<div class="flex flex-col h-full" :style="mobileSafeArea">
|
||||
<main class="flex flex-col flex-1 min-h-0">
|
||||
<div class="p-4">
|
||||
<NButton dashed block @click="handleAdd">
|
||||
New chat
|
||||
{{ $t('chat.newChatButton') }}
|
||||
</NButton>
|
||||
</div>
|
||||
<div class="flex-1 min-h-0 pb-4 overflow-hidden">
|
||||
<List />
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<NButton block @click="show = true">
|
||||
{{ $t('store.siderButton') }}
|
||||
</NButton>
|
||||
</div>
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
@@ -73,4 +91,5 @@ watch(
|
||||
<template v-if="isMobile">
|
||||
<div v-show="!collapsed" class="fixed inset-0 z-40 bg-black/40" @click="handleUpdateCollapsed" />
|
||||
</template>
|
||||
<PromptStore v-model:visible="show" />
|
||||
</template>
|
||||
|
||||