Compare commits

...

47 Commits

Author SHA1 Message Date
ChenZhaoYu
461d70a696 chore: 2.10.4 2023-03-11 16:31:55 +08:00
ChenZhaoYu
6b8ba6302a chore: format 2023-03-11 16:27:55 +08:00
ChenZhaoYu
c0a1b5606e feat: 设置添加关闭按钮 2023-03-11 16:16:35 +08:00
Nothing1024
00ade41a76 feat: 添加 Prompt 模板和 Prompt 商店支持 (#268)
* feat: 添加Prompt模板和Prompt商店支持

* feat: well done

---------

Co-authored-by: Redon <790348264@qq.com>
2023-03-11 16:09:52 +08:00
ChenZhaoYu
514ab7e9e4 chore: change docs 2023-03-11 10:50:58 +08:00
ChenZhaoYu
24c203f8d4 chore: v2.10.3 2023-03-10 14:48:42 +08:00
cloudGrin
cbcbdda4c0 chore: 简化docker-compose部署 (#466) 2023-03-10 14:33:36 +08:00
ChenZhaoYu
a2fcd31f24 perf: use hooks 2023-03-10 14:30:02 +08:00
ChenZhaoYu
07b92d4ede fix: 文字过长时头像被挤压 2023-03-10 14:20:56 +08:00
ChenZhaoYu
ed4ff67760 feat: 移动端按钮调整到顶部 2023-03-10 14:05:59 +08:00
ChenZhaoYu
9c4644c969 feat: iOS 安全距离 2023-03-10 14:04:50 +08:00
Xc
dd91c2a4e0 feat: support pwa (#452)
* feat: support pwa

* feat: support pwa
2023-03-10 13:25:30 +08:00
RyanzeX
7e8e15a628 fix: reset history title on clear (#453) 2023-03-10 13:24:36 +08:00
Yige
076c56d1d9 feat: 支持长回复 (#450)
* chore: rename environment variables files

* docs: update README.md about .env file

* feat: support long reply

* chore: upgrade chatgpt package and set long reply to false default

* chore: set long reply to false default
2023-03-10 13:23:22 +08:00
ChenZhaoYu
133a24e25f chore: update chatgpt 2023-03-10 13:11:36 +08:00
ChenZhaoYu
73a67b8f64 chore: 2.10.2_2 2023-03-10 00:47:56 +08:00
ChenZhaoYu
222b3eaa4c feat: 移动端下按钮收缩 2023-03-10 00:46:09 +08:00
ChenZhaoYu
c4baccdc48 chore: v2.10.2_1 2023-03-10 00:03:19 +08:00
ChenZhaoYu
7021a08ecf chore: reset scrollToBottom 2023-03-10 00:02:02 +08:00
ChenZhaoYu
e88b9bef13 chore: reset .env 2023-03-09 23:57:47 +08:00
ChenZhaoYu
c17cc16c0e chore: 异常打印和调整日志 2023-03-09 22:58:06 +08:00
ChenZhaoYu
d7d037618f chore: version 2.10.2 2023-03-09 22:49:15 +08:00
ChenZhaoYu
01edad7717 fix: 修复默认模型判断错误 2023-03-09 22:45:43 +08:00
ChenZhaoYu
eff787a2b7 chore: 移除两种报错 2023-03-09 20:16:18 +08:00
ChenZhaoYu
8616526136 fix: typo 2023-03-09 19:41:27 +08:00
ChenZhaoYu
32e3963390 chore: v2.10.1 2023-03-09 19:25:19 +08:00
ChenZhaoYu
7d52e6dd1e feat: model typo 2023-03-09 19:13:18 +08:00
ChenZhaoYu
ba41015df8 Merge branch 'feature' 2023-03-09 19:02:22 +08:00
ChenZhaoYu
f084460d1c fix: 深色模式导出图片的样式问题 2023-03-09 18:57:46 +08:00
Yige
a4ef23d603 chore: rename environment variables files (#395)
* chore: rename environment variables files

* docs: update README.md about .env file
2023-03-09 18:41:33 +08:00
xieccc
d3daa654a7 feat: 新增API模型配置项 (#404)
* chore: 更新文档

* Improve zh-TW locale (#379)

* fix: 移动端样式

* feat: typo

* fix: 调整滚动回原样

* feat: 新增API模型配置项

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
Co-authored-by: Peter Dave Hello <hsu@peterdavehello.org>
2023-03-09 18:38:30 +08:00
acongee
9576edf26f feat: 优化打字机模式显示新内容的逻辑 (#394)
* 添加为打字机模式优化的滚动至底部函数

* feat: 优化打字机模式始终显示最新内容的逻辑

* feat: 内容输出结束时也根据滚动条位置判断是否滚动至底部
2023-03-09 18:15:13 +08:00
CornerSkyless
5b74ac9cc6 fix: 修复导出图片会丢失头像的问题 (#392) 2023-03-09 17:59:26 +08:00
CornerSkyless
444e2ec2e8 feat: 增加了一个可以是否要发送历史上下文的开关 (#393)
* chore: 更新文档

* Improve zh-TW locale (#379)

* fix: 移动端样式

* feat: typo

* fix: 调整滚动回原样

* feat: 支持切换是否要发送前文信息

* style: 修复 lint

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
Co-authored-by: Peter Dave Hello <hsu@peterdavehello.org>
2023-03-09 17:56:11 +08:00
壳壳中的宇宙
60b7874f65 优化docker打包镜像文件过大的问题 (#415)
* chore: 更新文档

* Improve zh-TW locale (#379)

* fix: 移动端样式

* feat: typo

* fix: 调整滚动回原样

* 优化docker打包镜像文件过大

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
Co-authored-by: Peter Dave Hello <hsu@peterdavehello.org>
2023-03-09 17:52:39 +08:00
ChenZhaoYu
07cac12dac fix: 调整滚动回原样 2023-03-08 10:38:50 +08:00
ChenZhaoYu
4f3bfd1d4a feat: typo 2023-03-08 08:43:54 +08:00
ChenZhaoYu
451a456f58 fix: 移动端样式 2023-03-08 08:38:16 +08:00
Peter Dave Hello
5fe1e20e4a Improve zh-TW locale (#379) 2023-03-08 08:29:30 +08:00
ChenZhaoYu
54381ed2e2 chore: 更新文档 2023-03-07 22:23:44 +08:00
Redon
ffd4da91cf chore: version 2.10.0
* feat: 权限验证功能

* chore: v2.10.0

* feat: 500 服务异常页面

* feat: 只有结束才会滚动到底部

* chore: 修改 CHANGELOG

* chore: 不存在时输出默认报错
2023-03-07 22:12:15 +08:00
CornerSkyless
a2ffa3cb3a feat: 增加保存会话为图片的功能 (#374)
* feat: 增加保存会话为图片的功能

* feat: 异常处理和增加导出动画

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-07 21:13:41 +08:00
Peter Dave Hello
ecc2afd164 feat: 添加繁体中文翻译 (#348)
* feat: Add Traditional Chinese language UI locale

* chore: 添加新翻译

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-07 18:44:27 +08:00
Nine9
45cbfbf002 feat: 增加聊天记录导入导出清空的功能 (#369)
* feat: 增加聊天记录导入导出功能

* feat: 添加日期和图标

* perf: 移除触发事件改为 reload

---------

Co-authored-by: Nine9 <germmc99@gmail.com>
Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-07 18:26:55 +08:00
CornerSkyless
a689406b28 feat: 判断小窗模式 ctrl+enter 发送消息 (#363) 2023-03-07 17:54:22 +08:00
Redon
2ff82b1249 Merge pull request #370 from Chanzhaoyu/feature
feat: 转义状态码
2023-03-07 17:01:15 +08:00
ChenZhaoYu
8e1b4edc91 feat: 转义状态码 2023-03-07 16:59:47 +08:00
62 changed files with 3458 additions and 294 deletions

View File

@@ -1,6 +1,6 @@
**/node_modules
*/node_modules
node_modules
Dockerfile
.git
.husky
.github
.vscode
.*
*/.*

3
.env
View File

@@ -2,3 +2,6 @@
VITE_GLOB_API_URL=/api
VITE_APP_API_BASE_URL=http://localhost:3002/
# Whether long replies are supported, which may result in higher API fees
VITE_GLOB_OPEN_LONG_REPLY=false

3
.gitignore vendored
View File

@@ -27,3 +27,6 @@ coverage
*.njsproj
*.sln
*.sw?
# Environment variables files
/service/.env

View File

@@ -1,3 +1,119 @@
## v2.10.4
`2023-03-11`
## Feature
- 感谢 [Nothing1024](https://github.com/Chanzhaoyu/chatgpt-web/pull/268) 添加 `Prompt` 模板和 `Prompt` 商店支持
## Enhancement
- 设置添加关闭按钮[#495]
## Demo
![Prompt](https://camo.githubusercontent.com/6a51af751eb29238cb7ef4f8fbd89f63db837562f97f33273095424e62dc9194/68747470733a2f2f73312e6c6f63696d672e636f6d2f323032332f30332f30342f333036326665633163613562632e676966)
## 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
- 更新依赖到最新
## 演示
> 不是界面最新效果,有美化改动
权限
![权限](https://user-images.githubusercontent.com/24789441/223438518-80d58d42-e344-4e39-b87c-251ff73925ed.png)
聊天记录导出
![聊天记录导出](https://user-images.githubusercontent.com/57023771/223372153-6d8e9ec1-d82c-42af-b4bd-232e50504a25.gif)
保存图片到本地
![保存图片到本地](https://user-images.githubusercontent.com/13901424/223423555-b69b95ef-8bcf-4951-a7c9-98aff2677e18.gif)
## v2.9.3
`2023-03-06`

View File

@@ -4,7 +4,11 @@ FROM node:lts-alpine AS builder
COPY ./ /app
WORKDIR /app
RUN npm install pnpm -g && pnpm install && pnpm run build
RUN apk add --no-cache git \
&& npm install pnpm -g \
&& pnpm install \
&& pnpm run build \
&& rm -rf /root/.npm /root/.pnpm-store /usr/local/share/.cache /tmp/*
# service
FROM node:lts-alpine
@@ -13,8 +17,12 @@ COPY /service /app
COPY --from=builder /app/dist /app/public
WORKDIR /app
RUN npm install pnpm -g && pnpm install
RUN apk add --no-cache git \
&& npm install pnpm -g \
&& pnpm install --only=production \
&& rm -rf /root/.npm /root/.pnpm-store /usr/local/share/.cache /tmp/*
EXPOSE 3002
CMD ["pnpm", "run", "start"]
CMD ["pnpm", "run", "start"]

View File

@@ -55,7 +55,7 @@ Comparison:
[Details](https://github.com/Chanzhaoyu/chatgpt-web/issues/138)
Switching Methods:
1. Go to the `service/.env` file.
1. Go to the `service/.env.example` file and copy the contents to the `service/.env` file.
2. For `OpenAI API Key`, fill in the `OPENAI_API_KEY` field [(Get apiKey)](https://platform.openai.com/overview).
3. For `Web API`, fill in the `OPENAI_ACCESS_TOKEN` field [(Get accessToken)](https://chat.openai.com/api/auth/session).
4. When both are present, `OpenAI API Key` takes precedence.
@@ -84,6 +84,12 @@ For all parameter variables, check [here](#docker-parameter-example) or see:
[✓] Formatting and beautifying code-like message types
[✓] Access rights control
[✓] Data import and export
[✓] Save message to local image
[✓] Multilingual interface
[✓] Interface themes
@@ -162,7 +168,9 @@ pnpm dev
- `OPENAI_API_KEY` one of two
- `OPENAI_ACCESS_TOKEN` one of two, `OPENAI_API_KEY` takes precedence when both are present
- `OPENAI_API_BASE_URL` optional, available when `OPENAI_API_KEY` is set
- `OPENAI_API_MODEL` optional, available when `OPENAI_API_KEY` is set
- `API_REVERSE_PROXY` optional, available when `OPENAI_ACCESS_TOKEN` is set [Reference](#introduction)
- `AUTH_SECRET_KEY` Access Passwordoptional
- `TIMEOUT_MS` timeout, in milliseconds, optional
- `SOCKS_PROXY_HOST` optional, effective with SOCKS_PROXY_PORT
- `SOCKS_PROXY_PORT` optional, effective with SOCKS_PROXY_HOST
@@ -203,8 +211,12 @@ services:
OPENAI_ACCESS_TOKEN: xxxxxx
# api interface url, optional, available when OPENAI_API_KEY is set
OPENAI_API_BASE_URL: xxxx
# api model, optional, available when OPENAI_API_KEY is set
OPENAI_API_MODEL: xxxx
# reverse proxy, optional
API_REVERSE_PROXY: xxx
# access passwordoptional
AUTH_SECRET_KEY: xxx
# timeout, in milliseconds, optional
TIMEOUT_MS: 60000
# socks proxy, optional, effective with SOCKS_PROXY_PORT
@@ -213,6 +225,7 @@ services:
SOCKS_PROXY_PORT: xxxx
```
The `OPENAI_API_BASE_URL` is optional and only used when setting the `OPENAI_API_KEY`.
The `OPENAI_API_MODEL` is optional and only used when setting the `OPENAI_API_KEY`.
### Deployment with Railway
@@ -223,10 +236,12 @@ The `OPENAI_API_BASE_URL` is optional and only used when setting the `OPENAI_API
| Environment Variable | Required | Description |
| -------------------- | -------- | ------------------------------------------------------------------------------------------------- |
| `PORT` | Required | Default: `3002` |
| `TIMEOUT_MS` | Optional | Timeout in milliseconds. |
| `AUTH_SECRET_KEY` | Optional | access password |
| `TIMEOUT_MS` | Optional | Timeout in milliseconds |
| `OPENAI_API_KEY` | Optional | Required for `OpenAI API`. `apiKey` can be obtained from [here](https://platform.openai.com/overview). |
| `OPENAI_ACCESS_TOKEN`| Optional | Required for `Web API`. `accessToken` can be obtained from [here](https://chat.openai.com/api/auth/session).|
| `OPENAI_API_BASE_URL` | Optional, only for `OpenAI API` | API endpoint. |
| `OPENAI_API_MODEL` | Optional, only for `OpenAI API` | API model. |
| `API_REVERSE_PROXY` | Optional, only for `Web API` | Reverse proxy address for `Web API`. [Details](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy) |
| `SOCKS_PROXY_HOST` | Optional, effective with `SOCKS_PROXY_PORT` | Socks proxy. |
| `SOCKS_PROXY_PORT` | Optional, effective with `SOCKS_PROXY_HOST` | Socks proxy port. |
@@ -256,7 +271,7 @@ PS: You can also run `pnpm start` directly on the server without packaging.
#### Frontend webpage
1. Modify `VITE_APP_API_BASE_URL` in `.env` at the root directory to your actual backend interface address.
1. Refer to the root directory `.env.example` file content to create `.env` file, modify `VITE_APP_API_BASE_URL` in `.env` at the root directory to your actual backend interface address.
2. Run the following command in the root directory and then copy the files in the `dist` folder to the root directory of your website service.
[Reference information](https://cn.vitejs.dev/guide/static-deploy.html#building-the-app)

View File

@@ -51,10 +51,16 @@
1. `ChatGPTAPI` 使用 `gpt-3.5-turbo-0301` 通过官方`OpenAI`补全`API`模拟`ChatGPT`(最稳健的方法,但它不是免费的,并且没有使用针对聊天进行微调的模型)
2. `ChatGPTUnofficialProxyAPI` 使用非官方代理服务器访问 `ChatGPT` 的后端`API`,绕过`Cloudflare`(使用真实的的`ChatGPT`,非常轻量级,但依赖于第三方服务器,并且有速率限制)
[查看详情](https://github.com/Chanzhaoyu/chatgpt-web/issues/138)
警告:
1. 你应该使用 `API` 方式并自建代理使你使用的风险降到最低。
2. 使用 `accessToken` 方式时反向代理将向第三方暴露您的访问令牌。这样做应该不会产生任何不良影响,但在使用这种方法之前请考虑风险,修改代理地址时也请使用公开的[社区方案](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy),不要不要不要使用来源不明的地址!
2. 因为国内 `API` 被墙,如果服务器不在国外,则需要代理才能请求到官方接口,也非常不建议使用别人发出来的代理地址,请自己搭建。
3. 人性是丑陋的,你永远不知道你相信的某些乐于分享的`好人`在用你的账号做什么!!!
注:强烈建议使用`ChatGPTAPI`,因为它使用 `OpenAI` 官方支持的`API`。并且可能会在将来的版本中删除对`ChatGPTUnofficialProxyAPI`的支持。
切换方式:
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` 优先
@@ -83,6 +89,12 @@ API_REVERSE_PROXY=
[✓] 对代码等消息类型的格式化美化处理
[✓] 访问权限控制
[✓] 数据导入、导出
[✓] 保存消息到本地图片
[✓] 界面多语言
[✓] 界面主题
@@ -160,7 +172,9 @@ pnpm dev
- `OPENAI_API_KEY` 二选一
- `OPENAI_ACCESS_TOKEN` 二选一,同时存在时,`OPENAI_API_KEY` 优先
- `OPENAI_API_BASE_URL` 可选,设置 `OPENAI_API_KEY` 时可用
- `OPENAI_API_MODEL` 可选,设置 `OPENAI_API_KEY` 时可用
- `API_REVERSE_PROXY` 可选,设置 `OPENAI_ACCESS_TOKEN` 时可用 [参考](#介绍)
- `AUTH_SECRET_KEY` 访问权限密钥,可选
- `TIMEOUT_MS` 超时,单位毫秒,可选
- `SOCKS_PROXY_HOST` 可选,和 SOCKS_PROXY_PORT 一起时生效
- `SOCKS_PROXY_PORT` 可选,和 SOCKS_PROXY_HOST 一起时生效
@@ -201,8 +215,12 @@ services:
OPENAI_ACCESS_TOKEN: xxxxxx
# API接口地址可选设置 OPENAI_API_KEY 时可用
OPENAI_API_BASE_URL: xxxx
# API模型可选设置 OPENAI_API_KEY 时可用
OPENAI_API_MODEL: xxxx
# 反向代理,可选
API_REVERSE_PROXY: xxx
# 访问权限密钥,可选
AUTH_SECRET_KEY: xxx
# 超时,单位毫秒,可选
TIMEOUT_MS: 60000
# Socks代理可选和 SOCKS_PROXY_PORT 一起时生效
@@ -211,6 +229,7 @@ services:
SOCKS_PROXY_PORT: xxxx
```
- `OPENAI_API_BASE_URL` 可选,设置 `OPENAI_API_KEY` 时可用
- `OPENAI_API_MODEL` 可选,设置 `OPENAI_API_KEY` 时可用
### 使用 Railway 部署
[![Deploy on Railway](https://railway.app/button.svg)](https://railway.app/new/template/yytmgc)
@@ -219,11 +238,13 @@ services:
| 环境变量名称 | 必填 | 备注 |
| --------------------- | ---------------------- | -------------------------------------------------------------------------------------------------- |
| `PORT` | 必填 | 默认 `3002` |
| `TIMEOUT_MS` | 可选 | 超时时间,单位毫秒, |
| `PORT` | 必填 | 默认 `3002`
| `AUTH_SECRET_KEY` | 可选 | 访问权限密钥 |
| `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代理端口 |
@@ -251,7 +272,7 @@ PS: 不进行打包,直接在服务器上运行 `pnpm start` 也可
#### 前端网页
1、修改根目录下 `.env` `VITE_APP_API_BASE_URL` 为你的实际后端接口地址
1、修改根目录下 `.env` 文件中的 `VITE_APP_API_BASE_URL` 为你的实际后端接口地址
2、根目录下运行以下命令然后将 `dist` 文件夹内的文件复制到你网站服务的根目录下

View File

@@ -12,8 +12,12 @@ services:
OPENAI_ACCESS_TOKEN: xxxxxx
# API接口地址可选设置 OPENAI_API_KEY 时可用
OPENAI_API_BASE_URL: xxxx
# API模型可选设置 OPENAI_API_KEY 时可用
OPENAI_API_MODEL: xxxx
# 反向代理,可选
API_REVERSE_PROXY: xxx
# 访问权限密钥,可选
AUTH_SECRET_KEY: xxx
# 超时,单位毫秒,可选
TIMEOUT_MS: 60000
# Socks代理可选和 SOCKS_PROXY_PORT 一起时生效
@@ -21,13 +25,13 @@ services:
# Socks代理端口可选和 SOCKS_PROXY_HOST 一起时生效
SOCKS_PROXY_PORT: xxxx
nginx:
build: nginx
image: chatgpt/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

View File

@@ -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;"]

View File

@@ -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 {

View File

@@ -1,8 +1,7 @@
### docker-compose 部署教程
- 将打包好的前端文件放到 `nginx/html` 目录下
- ```shell
# 打包启动
docker-compose build
# 启动
docker-compose up -d
```
- ```shell

View File

@@ -1,6 +1,6 @@
{
"name": "chatgpt-web",
"version": "2.9.3",
"version": "2.10.4",
"private": false,
"description": "ChatGPT Web",
"author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>",
@@ -26,6 +26,7 @@
"@traptitech/markdown-it-katex": "^3.6.0",
"@vueuse/core": "^9.13.0",
"highlight.js": "^11.7.0",
"html2canvas": "^1.4.1",
"katex": "^0.16.4",
"markdown-it": "^13.0.1",
"naive-ui": "^2.34.3",
@@ -57,6 +58,7 @@
"tailwindcss": "^3.2.7",
"typescript": "~4.9.5",
"vite": "^4.1.4",
"vite-plugin-pwa": "^0.14.4",
"vue-tsc": "^1.2.0"
},
"lint-staged": {

1885
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

BIN
public/pwa-192x192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

BIN
public/pwa-512x512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

View File

@@ -7,12 +7,18 @@ 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=
# Reverse Proxy
API_REVERSE_PROXY=
# timeout
TIMEOUT_MS=100000
# Secret key
AUTH_SECRET_KEY=
# Socks Proxy Host
SOCKS_PROXY_HOST=

View File

@@ -24,7 +24,7 @@
"common:cleanup": "rimraf node_modules && rimraf pnpm-lock.yaml"
},
"dependencies": {
"chatgpt": "^5.0.7",
"chatgpt": "^5.0.9",
"dotenv": "^16.0.3",
"esno": "^0.16.3",
"express": "^4.18.2",

View File

@@ -4,7 +4,7 @@ specifiers:
'@antfu/eslint-config': ^0.35.3
'@types/express': ^4.17.17
'@types/node': ^18.14.6
chatgpt: ^5.0.7
chatgpt: ^5.0.9
dotenv: ^16.0.3
eslint: ^8.35.0
esno: ^0.16.3
@@ -17,7 +17,7 @@ specifiers:
typescript: ^4.9.5
dependencies:
chatgpt: 5.0.7
chatgpt: 5.0.9
dotenv: 16.0.3
esno: 0.16.3
express: 4.18.2
@@ -902,8 +902,8 @@ packages:
resolution: {integrity: sha512-mKKUkUbhPpQlCOfIuZkvSEgktjPFIsZKRRbC6KWVEMvlzblj3i3asQv5ODsrwt0N3pHAEvjP8KTQPHkp0+6jOg==}
dev: true
/chatgpt/5.0.7:
resolution: {integrity: sha512-wy69++JDNS0xKi+6rP+HDOByXBafQIVynHnlQw09apuDntGSKfwBRY902N8Q7/ZFU/XET+8NpJiio2iI69IWYw==}
/chatgpt/5.0.9:
resolution: {integrity: sha512-H0MMegLKcYyYh3LeFO4ubIdJSiSAl4rRjTeXf3KjHfGXDM7QZ1EkiTH9RuIoaNzOm8rJTn4QEhrwBbOIpbalxw==}
engines: {node: '>=14'}
hasBin: true
dependencies:

View File

@@ -7,6 +7,15 @@ import fetch from 'node-fetch'
import { sendResponse } from '../utils'
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
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',
}
dotenv.config()
const timeoutMs: number = !isNaN(+process.env.TIMEOUT_MS) ? +process.env.TIMEOUT_MS : 30 * 1000
@@ -22,11 +31,14 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
// More Info: https://github.com/transitive-bullshit/chatgpt-api
if (process.env.OPENAI_API_KEY) {
const OPENAI_API_MODEL = process.env.OPENAI_API_MODEL
const model = (typeof OPENAI_API_MODEL === 'string' && OPENAI_API_MODEL.length > 0)
? OPENAI_API_MODEL
: 'gpt-3.5-turbo'
const options: ChatGPTAPIOptions = {
apiKey: process.env.OPENAI_API_KEY,
completionParams: {
model: 'gpt-3.5-turbo',
},
completionParams: { model },
debug: false,
}
@@ -75,8 +87,8 @@ async function chatReplyProcess(
lastContext?: { conversationId?: string; parentMessageId?: string },
process?: (chat: ChatMessage) => void,
) {
if (!message)
return sendResponse({ type: 'Fail', message: 'Message is empty' })
// if (!message)
// return sendResponse({ type: 'Fail', message: 'Message is empty' })
try {
let options: SendMessageOptions = { timeoutMs }
@@ -98,8 +110,11 @@ async function chatReplyProcess(
return sendResponse({ type: 'Success', data: response })
}
catch (error: any) {
global.console.error(error)
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' })
}
}

View File

@@ -1,6 +1,7 @@
import express from 'express'
import type { ChatContext, ChatMessage } from './chatgpt'
import { chatConfig, chatReplyProcess } from './chatgpt'
import { auth } from './middleware/auth'
const app = express()
const router = express.Router()
@@ -15,7 +16,7 @@ app.all('*', (_, res, next) => {
next()
})
router.post('/chat-process', async (req, res) => {
router.post('/chat-process', auth, async (req, res) => {
res.setHeader('Content-type', 'application/octet-stream')
try {
@@ -44,6 +45,33 @@ router.post('/config', async (req, res) => {
}
})
router.post('/session', async (req, res) => {
try {
const AUTH_SECRET_KEY = process.env.AUTH_SECRET_KEY
const hasAuth = typeof AUTH_SECRET_KEY === 'string' && AUTH_SECRET_KEY.length > 0
res.send({ status: 'Success', message: '', data: { auth: hasAuth } })
}
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)

View File

@@ -0,0 +1,19 @@
const auth = async (req, res, next) => {
const AUTH_SECRET_KEY = process.env.AUTH_SECRET_KEY
if (typeof AUTH_SECRET_KEY === 'string' && AUTH_SECRET_KEY.length > 0) {
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 }

View File

@@ -33,3 +33,16 @@ export function fetchChatAPIProcess<T = any>(
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 },
})
}

View File

@@ -0,0 +1,8 @@
[
{
"key": "awesome-chatgpt-prompts-zh",
"desc": "ChatGPT 中文调教指南",
"downloadUrl": "https://raw.githubusercontent.com/Nothing1024/chatgpt-prompt-collection/main/awesome-chatgpt-prompts-zh.json",
"url": "https://github.com/PlexPt/awesome-chatgpt-prompts-zh"
}
]

View File

@@ -0,0 +1,429 @@
<script setup lang='ts'>
import type { DataTableColumns } from 'naive-ui'
import { computed, h, ref, watch } from 'vue'
import { NButton, NCard, NDataTable, NDivider, NGi, NGrid, NInput, NLayoutContent, NMessageProvider, NModal, NPopconfirm, NSpace, NTabPane, NTabs, useMessage } from 'naive-ui'
import PromptRecommend from '../../../assets/recommend.json'
import { SvgIcon } from '..'
import { usePromptStore } from '@/store'
import { useBasicLayout } from '@/hooks/useBasicLayout'
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 { 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: string, 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('已存在重复标题,请重新输入')
return
}
if (i.value === tempPromptValue.value) {
message.error(`已存在重复内容:${tempPromptKey.value},请重新输入`)
return
}
}
promptList.value.unshift({ key: tempPromptKey.value, value: tempPromptValue.value } as never)
message.success('添加 prompt 成功')
changeShowModal('')
}
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('检测修改 Prompt 标题冲突,请重新修改')
return
}
if (i.value === tempPromptValue.value) {
message.error(`检测修改内容${i.key}冲突,请重新修改`)
return
}
}
promptList.value = [{ key: tempPromptKey.value, value: tempPromptValue.value }, ...tempList] as never
message.success('Prompt 信息修改成功')
changeShowModal('')
}
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('删除 Prompt 成功')
}
const clearPromptTemplate = () => {
promptList.value = []
message.success('清空 Prompt 成功')
}
const importPromptTemplate = () => {
try {
const jsonData = JSON.parse(tempPromptValue.value)
for (const i of jsonData) {
let safe = true
for (const j of promptList.value) {
if (j.key === i.key) {
message.warning(`因标题重复跳过:${i.key}`)
safe = false
break
}
if (j.value === i.value) {
message.warning(`因内容重复跳过:${i.key}`)
safe = false
break
}
}
if (safe)
promptList.value.unshift({ key: i.key, value: i.value } as never)
}
message.success('导入成功')
changeShowModal('')
}
catch {
message.error('JSON 格式错误,请检查 JSON 格式')
changeShowModal('')
}
}
// 模板导出
const exportPromptTemplate = () => {
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)
}
// 模板在线导入
const downloadPromptTemplate = async () => {
try {
await fetch(downloadURL.value)
.then(response => response.json())
.then((jsonData) => {
tempPromptValue.value = JSON.stringify(jsonData)
}).then(() => {
importPromptTemplate()
})
}
catch {
message.error('网络导入出现问题,请检查网络状态与 JSON 文件有效性')
}
}
// 移动端自适应相关
const renderTemplate = () => {
const [keyLimit, valueLimit] = isMobile.value ? [6, 9] : [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: '标题',
key: 'renderKey',
minWidth: 100,
},
{
title: '内容',
key: 'renderValue',
},
{
title: '操作',
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: () => '修改' },
),
h(
NButton,
{
tertiary: true,
size: 'small',
type: 'error',
onClick: () => deletePromptTemplate(row),
},
{ default: () => '删除' },
),
],
})
},
},
]
}
const columns = createColumns()
watch(
() => promptList,
() => {
promptStore.updatePromptList(promptList.value)
},
{ deep: true },
)
</script>
<template>
<NMessageProvider>
<NModal v-model:show="show" style="width: 90%; max-width: 900px;" preset="card">
<NCard>
<div class="space-y-4">
<NTabs type="segment">
<NTabPane name="local" tab="本地管理">
<NSpace justify="end">
<NButton type="primary" @click="changeShowModal('add')">
添加
</NButton>
<NButton @click="changeShowModal('local_import')">
导入
</NButton>
<NButton @click="exportPromptTemplate()">
导出
</NButton>
<NPopconfirm @positive-click="clearPromptTemplate">
<template #trigger>
<NButton>
清空
</NButton>
</template>
确认是否清空数据?
</NPopconfirm>
</NSpace>
<br>
<NDataTable
:max-height="400"
:columns="columns"
:data="renderTemplate()"
:pagination="pagination"
:bordered="false"
/>
</NTabPane>
<NTabPane name="download" tab="在线导入">
注意请检查下载 JSON 文件来源恶意的JSON文件可能会破坏您的计算机<br><br>
<NGrid x-gap="12" y-gap="12" :cols="24">
<NGi :span="isMobile ? 18 : 22">
<NInput v-model:value="downloadURL" placeholder="请输入正确的 JSON 地址" />
</NGi>
<NGi>
<NButton strong secondary :disabled="downloadDisabled" @click="downloadPromptTemplate()">
下载
</NButton>
</NGi>
</NGrid>
<NDivider />
<NLayoutContent v-if="isMobile" style="height: 360px" content-style=" background:none;" :native-scrollbar="false">
<NCard
v-for="info in promptRecommendList"
:key="info.key" :title="info.key"
style="margin: 5px;"
embedded
:bordered="true"
>
{{ info.desc }}
<template #footer>
<NSpace justify="end">
<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>
</NSpace>
</template>
</NCard>
</NLayoutContent>
<NLayoutContent
v-else
style="height: 360px"
content-style="padding: 10px; background:none;"
:native-scrollbar="false"
>
<NGrid x-gap="12" y-gap="12" :cols="isMobile ? 1 : 3">
<NGi v-for="info in promptRecommendList" :key="info.key">
<NCard :title="info.key" embedded :bordered="true">
{{ info.desc }}
<template #footer>
<NSpace justify="end">
<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>
</NSpace>
</template>
</NCard>
</NGi>
</NGrid>
</NLayoutContent>
</NTabPane>
</NTabs>
</div>
</NCard>
</NModal>
<NModal v-model:show="showModal">
<NCard
style="width: 600px"
:bordered="false"
size="huge"
role="dialog"
aria-modal="true"
>
<NSpace v-if="modalMode === 'add' || modalMode === 'modify'" vertical>
模板标题
<NInput v-model:value="tempPromptKey" placeholder="搜索" />
模板内容
<NInput v-model:value="tempPromptValue" placeholder="搜索" type="textarea" />
<NButton
strong
secondary
:style="{ width: '100%' }"
:disabled="inputStatus"
@click="() => { modalMode === 'add' ? addPromptTemplate() : modifyPromptTemplate() }"
>
确定
</NButton>
</NSpace>
<NSpace v-if="modalMode === 'local_import'" vertical>
<NInput
v-model:value="tempPromptValue"
placeholder="请粘贴json文件内容"
:autosize="{ minRows: 3, maxRows: 15 }"
type="textarea"
/>
<NButton
strong
secondary
:style="{ width: '100%' }"
:disabled="inputStatus"
@click="() => { importPromptTemplate() }"
>
导入
</NButton>
</NSpace>
</NCard>
</NModal>
</NMessageProvider>
</template>

View File

@@ -1,18 +1,13 @@
<script lang="ts" setup>
import { computed, ref } from 'vue'
import { NButton, NInput, useMessage } from 'naive-ui'
import { NButton, NInput, NPopconfirm, 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 { t } from '@/locales'
interface Emit {
(event: 'update'): void
}
const emit = defineEmits<Emit>()
const appStore = useAppStore()
const userStore = useUserStore()
@@ -56,7 +51,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 +64,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 +147,75 @@ 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>
<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">
<div class="flex flex-wrap items-center gap-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']"
<NButton
size="small"
:type="item.key === language ? 'primary' : undefined"
@click="appStore.setLanguage(item.key)"
>
<span class="text-sm">
{{ item.label }}
</span>
</a>
{{ item.label }}
</NButton>
</template>
</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>

View File

@@ -1,6 +1,6 @@
<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 About from './About.vue'
import { SvgIcon } from '@/components/common'
@@ -19,8 +19,6 @@ interface Emit {
const active = ref('General')
const reload = ref(false)
const show = computed({
get() {
return props.visible
@@ -29,18 +27,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 +39,7 @@ 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 name="Config" tab="Config">
@@ -59,6 +50,6 @@ function handleReload() {
<About />
</NTabPane>
</NTabs>
</NCard>
</div>
</NModal>
</template>

View File

@@ -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"

View File

@@ -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 }

View File

@@ -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

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 19 KiB

5
src/icons/403.vue Normal file

File diff suppressed because one or more lines are too long

5
src/icons/500.vue Normal file

File diff suppressed because one or more lines are too long

View File

@@ -3,12 +3,17 @@ export default {
delete: 'Delete',
save: 'Save',
reset: 'Reset',
export: 'Export',
import: 'Import',
clear: 'Clear',
yes: 'Yes',
no: 'No',
noData: 'No Data',
wrong: 'Something went wrong, please try again later.',
success: 'Success',
failed: 'Failed',
verify: 'Verify',
unauthorizedTips: 'Unauthorized, please verify first.',
},
chat: {
placeholder: 'Ask me anything...(Shift + Enter = line break)',
@@ -18,9 +23,17 @@ 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?',
},
setting: {
setting: 'Setting',
@@ -30,6 +43,7 @@ export default {
name: 'Name',
description: 'Description',
resetUserInfo: 'Reset UserInfo',
chatHistory: 'ChatHistory',
theme: 'Theme',
language: 'Language',
api: 'API',

View File

@@ -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,8 +15,9 @@ const i18n = createI18n({
fallbackLocale: 'en-US',
allowComposition: true,
messages: {
'en-US': en,
'zh-CN': cn,
'en-US': enUS,
'zh-CN': zhCN,
'zh-TW': zhTW,
},
})

View File

@@ -3,24 +3,37 @@ export default {
delete: '删除',
save: '保存',
reset: '重置',
export: '导出',
import: '导入',
clear: '清空',
yes: '是',
no: '否',
noData: '暂无数据',
wrong: '好像出错了,请稍后再试。',
success: '操作成功',
failed: '操作失败',
verify: '验证',
unauthorizedTips: '未经授权,请先进行验证。',
},
chat: {
placeholder: '来说点什么...Shift + Enter = 换行)',
placeholder: '来说点什么...Shift + Enter = 换行)',
placeholderMobile: '来说点什么...',
copy: '复制',
copied: '复制成功',
copyCode: '复制代码',
clearChat: '清空会话',
clearChatConfirm: '是否清空会话?',
exportImage: '保存会话到图片',
exportImageConfirm: '是否将会话保存为图片?',
exportSuccess: '保存成功',
exportFailed: '保存失败',
usingContext: '上下文模式',
turnOnContext: '当前模式下, 发送消息会携带之前的聊天记录',
turnOffContext: '当前模式下, 发送消息不会携带之前的聊天记录',
deleteMessage: '删除消息',
deleteMessageConfirm: '是否删除此消息?',
deleteHistoryConfirm: '确定删除此记录?',
clearHistoryConfirm: '确定清空聊天记录?',
},
setting: {
setting: '设置',
@@ -30,6 +43,7 @@ export default {
name: '名称',
description: '描述',
resetUserInfo: '重置用户信息',
chatHistory: '聊天记录',
theme: '主题',
language: '语言',
api: 'API',

53
src/locales/zh-TW.ts Normal file
View File

@@ -0,0 +1,53 @@
export default {
common: {
delete: '刪除',
save: '儲存',
reset: '重設',
export: '匯出',
import: '匯入',
clear: '清除',
yes: '是',
no: '否',
noData: '暫無資料',
wrong: '好像出錯了,請稍後再試。',
success: '操作成功',
failed: '操作失敗',
verify: '驗證',
unauthorizedTips: '未經授權,請先進行驗證。',
},
chat: {
placeholder: '來說點什麼...Shift + Enter = 換行)',
placeholderMobile: '來說點什麼...',
copy: '複製',
copied: '複製成功',
copyCode: '複製代碼',
clearChat: '清除對話',
clearChatConfirm: '是否清空對話?',
exportImage: '儲存對話為圖片',
exportImageConfirm: '是否將對話儲存為圖片?',
exportSuccess: '儲存成功',
exportFailed: '儲存失敗',
usingContext: '上下文模式',
turnOnContext: '在當前模式下, 發送訊息會攜帶之前的聊天記錄。',
turnOffContext: '在當前模式下, 發送訊息不會攜帶之前的聊天記錄。',
deleteMessage: '刪除訊息',
deleteMessageConfirm: '是否刪除此訊息?',
deleteHistoryConfirm: '確定刪除此紀錄?',
},
setting: {
setting: '設定',
general: '總覽',
config: '設定',
avatarLink: '頭貼連結',
name: '名稱',
description: '描述',
resetUserInfo: '重設使用者資訊',
chatHistory: '紀錄',
theme: '主題',
language: '語言',
api: 'API',
reverseProxy: '反向代理',
timeout: '逾時',
socks: 'Socks',
},
}

View File

@@ -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()

25
src/router/permission.ts Normal file
View File

@@ -0,0 +1,25 @@
import type { Router } from 'vue-router'
import { useAuthStoreWithout } from '@/store/modules/auth'
export function setupPageGuard(router: Router) {
router.beforeEach(async (from, to, next) => {
const authStore = useAuthStoreWithout()
if (!authStore.session) {
try {
const data = await authStore.getSession()
if (String(data.auth) === 'false' && authStore.token)
authStore.removeToken()
next()
}
catch (error) {
if (from.path !== '/500')
next({ name: '500' })
else
next()
}
}
else {
next()
}
})
}

View File

@@ -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

View 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)
}

View File

@@ -0,0 +1,43 @@
import { defineStore } from 'pinia'
import { getToken, removeToken, setToken } from './helper'
import { store } from '@/store'
import { fetchSession } from '@/api'
export interface AuthState {
token: string | undefined
session: { auth: boolean } | null
}
export const useAuthStore = defineStore('auth-store', {
state: (): AuthState => ({
token: getToken(),
session: null,
}),
actions: {
async getSession() {
try {
const { data } = await fetchSession<{ auth: boolean }>()
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)
}

View File

@@ -165,6 +165,7 @@ export const useChatStore = defineStore('chat-store', {
if (!uuid || uuid === 0) {
if (this.chat.length) {
this.chat[0].data = []
this.history[0].title = 'New Chat'
this.recordState()
}
return
@@ -173,6 +174,7 @@ export const useChatStore = defineStore('chat-store', {
const index = this.chat.findIndex(item => item.uuid === uuid)
if (index !== -1) {
this.chat[index].data = []
this.history[index].title = 'New Chat'
this.recordState()
}
},

View File

@@ -1,3 +1,5 @@
export * from './app'
export * from './chat'
export * from './user'
export * from './prompt'
export * from './auth'

View 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)
}

View 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
},
},
})

View File

@@ -6,4 +6,5 @@ body,
body {
padding-bottom: constant(safe-area-inset-bottom);
padding-bottom: env(safe-area-inset-bottom);
}

View 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}`
}

View File

@@ -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) => {

View File

@@ -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)
}

View 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>

View File

@@ -38,7 +38,7 @@ const wrapClass = computed(() => {
'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]',
{ 'text-red-500': props.error },

View File

@@ -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 = 50 // 阈值,表示滚动条到底部的距离阈值
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,
}
}

View File

@@ -0,0 +1,21 @@
import { ref } from 'vue'
import { useMessage } from 'naive-ui'
import { t } from '@/locales'
export function useUsingContext() {
const ms = useMessage()
const usingContext = ref<boolean>(true)
function toggleUsingContext() {
usingContext.value = !usingContext.value
if (usingContext.value)
ms.success(t('chat.turnOnContext'))
else
ms.warning(t('chat.turnOffContext'))
}
return {
usingContext,
toggleUsingContext,
}
}

View File

@@ -1,28 +1,37 @@
<script setup lang='ts'>
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 { usingContext, toggleUsingContext } = useUsingContext()
const { uuid } = route.params as { uuid: string }
@@ -32,12 +41,17 @@ const conversationList = computed(() => dataSources.value.filter(item => (!item.
const prompt = ref<string>('')
const loading = ref<boolean>(false)
// 添加PromptStore
const promptStore = usePromptStore()
// 使用storeToRefs保证store修改后联想部分能够重新渲染
const { promptList: promptTemplate } = storeToRefs<any>(promptStore)
function handleSubmit() {
onConversation()
}
async function onConversation() {
const message = prompt.value
let message = prompt.value
if (loading.value)
return
@@ -66,7 +80,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 +98,53 @@ 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')
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: false,
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()
}
scrollToBottom()
}
catch (error) {
//
}
},
})
}
},
})
}
await fetchChatAPIOnce()
}
catch (error: any) {
const errorMessage = error?.message ?? t('common.wrong')
@@ -177,7 +204,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 +228,50 @@ 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')
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: false,
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) {
//
}
},
})
}
await fetchChatAPIOnce()
}
catch (error: any) {
if (error.message === 'canceled') {
@@ -268,6 +306,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 +385,12 @@ function handleEnter(event: KeyboardEvent) {
handleSubmit()
}
}
else {
if (event.key === 'Enter' && event.ctrlKey) {
event.preventDefault()
handleSubmit()
}
}
}
function handleStop() {
@@ -314,6 +400,31 @@ 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,16 +435,10 @@ const buttonDisabled = computed(() => {
return loading.value || !prompt.value || prompt.value.trim() === ''
})
const wrapClass = computed(() => {
if (isMobile.value)
return ['pt-14']
return []
})
const footerClass = computed(() => {
let classes = ['p-4']
if (isMobile.value)
classes = ['sticky', 'left-0', 'bottom-0', 'right-0', 'p-2', 'pr-4', 'overflow-hidden']
classes = ['sticky', 'left-0', 'bottom-0', 'right-0', 'p-2', 'pr-3', 'overflow-hidden']
return classes
})
@@ -348,15 +453,24 @@ onUnmounted(() => {
</script>
<template>
<div class="flex flex-col w-full 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']"
>
<div class="w-full max-w-screen-xl m-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" />
@@ -397,13 +511,30 @@ onUnmounted(() => {
<SvgIcon icon="ri:delete-bin-line" />
</span>
</HoverButton>
<NInput
v-model:value="prompt"
type="textarea"
:autosize="{ minRows: 1, maxRows: 2 }"
:placeholder="placeholder"
@keypress="handleEnter"
/>
<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
v-model:value="prompt"
type="textarea"
:placeholder="placeholder"
:autosize="{ minRows: 1, maxRows: 2 }"
@input="handleInput"
@focus="handleFocus"
@blur="handleBlur"
@keypress="handleEnter"
/>
</template>
</NAutoComplete>
<NButton type="primary" :disabled="buttonDisabled" @click="handleSubmit">
<template #icon>
<span class="dark:text-black">

View File

@@ -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>

View File

@@ -0,0 +1,81 @@
<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="text" placeholder="" @keypress="handlePress" />
<NButton
block
type="primary"
:disabled="disabled"
:loading="loading"
@click="handleVerify"
>
{{ $t('common.verify') }}
</NButton>
</div>
</div>
</NModal>
</template>

View File

@@ -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>

View File

@@ -9,8 +9,9 @@ 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">
<span class="text-xl text-[#4f555e] dark:text-white">
<SvgIcon icon="ri:settings-4-line" />

View File

@@ -1,16 +1,18 @@
<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)
@@ -75,6 +77,11 @@ watch(
<div class="flex-1 min-h-0 pb-4 overflow-hidden">
<List />
</div>
<div class="p-4">
<NButton block @click="show = true">
Prompt Store
</NButton>
</div>
</main>
<Footer />
</div>
@@ -82,4 +89,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>

View File

@@ -1,34 +0,0 @@
<script lang="ts" setup>
import { NButton } from 'naive-ui'
import { useRouter } from 'vue-router'
const router = useRouter()
function goHome() {
router.push('/')
}
</script>
<template>
<div class="flex h-full">
<div class="px-4 m-auto space-y-4 text-center max-[400px]">
<h1 class="text-4xl text-slate-800 dark:text-neutral-200">
No permission
</h1>
<p class="text-base text-slate-500 dark:text-neutral-400">
The page you're trying access has restricted access.
Please refer to your system administrator
</p>
<div class="flex items-center justify-center text-center">
<div class="w-[300px]">
<div class="w-[300px]">
<img src="../../../icons/403.svg" alt="404">
</div>
</div>
</div>
<NButton type="primary" @click="goHome">
Go to Home
</NButton>
</div>
</div>
</template>

View File

@@ -0,0 +1,32 @@
<script lang="ts" setup>
import { NButton } from 'naive-ui'
import { useRouter } from 'vue-router'
import Icon500 from '@/icons/500.vue'
const router = useRouter()
function goHome() {
router.push('/')
}
</script>
<template>
<div class="flex h-full dark:bg-neutral-800">
<div class="px-4 m-auto space-y-4 text-center max-[400px]">
<header class="space-y-2">
<h2 class="text-2xl font-bold text-center text-slate-800 dark:text-neutral-200">
500
</h2>
<p class="text-base text-center text-slate-500 dark:text-slate-500">
Server error
</p>
<div class="flex items-center justify-center text-center">
<Icon500 class="w-[300px]" />
</div>
</header>
<NButton type="primary" @click="goHome">
Go to Home
</NButton>
</div>
</div>
</template>

View File

@@ -1,6 +1,7 @@
import path from 'path'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig((env) => {
const viteEnv = loadEnv(env.mode, process.cwd()) as unknown as ImportMetaEnv
@@ -11,7 +12,20 @@ export default defineConfig((env) => {
'@': path.resolve(process.cwd(), 'src'),
},
},
plugins: [vue()],
plugins: [
vue(),
VitePWA({
injectRegister: 'auto',
manifest: {
name: 'chatGPT',
short_name: 'chatGPT',
icons: [
{ src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' },
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' },
],
},
}),
],
server: {
host: '0.0.0.0',
port: 1002,