Compare commits

...

35 Commits

Author SHA1 Message Date
ChenZhaoYu
cf788b190a chore: v2.10.5 2023-03-13 10:00:56 +08:00
Eason
6cd16826fd chore: optimize dockerfile to speed up building and reduce docker image size (#520) 2023-03-13 09:03:17 +08:00
ChenZhaoYu
b288cd612e chore: docs change 2023-03-13 08:58:30 +08:00
ChenZhaoYu
efc9e81e83 fix: 清空上下文时不应该重置会话标题 2023-03-13 08:49:21 +08:00
ChenZhaoYu
db502e1412 feat: 权限输入框改为密码类型 2023-03-13 08:48:44 +08:00
ChenZhaoYu
41ddc6a8e1 chore: docs change 2023-03-13 08:44:53 +08:00
ChenZhaoYu
0481726608 feat: 修改 Prompt Store 移动端样式 2023-03-13 08:24:13 +08:00
ChenZhaoYu
73bf8c01a9 feat: 语言设定改为下拉框选择 2023-03-13 08:21:02 +08:00
Peter Dave Hello
8a0cb90ccc feat: improve zh-TW locale, translate new strings (#542) 2023-03-13 08:11:22 +08:00
ChenZhaoYu
f4be5b985a chore: update deps 2023-03-12 21:10:40 +08:00
ChenZhaoYu
0a9f9b618b feat: 调整界面 2023-03-12 21:08:32 +08:00
ChenZhaoYu
af76b89fd4 feat: 仓库查询筛选 2023-03-12 20:57:21 +08:00
ChenZhaoYu
de6632d631 feat: 仓库添加翻译 2023-03-12 20:49:10 +08:00
吴杉(Shan Wu)
7bebee202e fix: Prompt商店在线导入可以导入两种recommend.json里提到的模板 (#516) (#521)
* fix(PromptStore): import prompt template using different dict keys

* chore(PromptStore): clear url field after downloading
2023-03-12 19:42:56 +08:00
Eason
bc5e835f78 feat: support linux command line proxy standard (#308)
* feat: support linux command line proxy standard with env HTTPS_PROXY and ALL_PROXY

* chore: update docs for linux command linux proxy standard
2023-03-12 19:38:59 +08:00
Yige
a4cfd0c380 fix: 修改最大行数与官方保持一致 (#502)
* 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

* fix: change maxRows to 8

* feat: mobile max row

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-12 19:29:04 +08:00
Yige
86d720ecee fix: cors in auth_secret_key model (#499) 2023-03-12 18:47:44 +08:00
Peter Dave Hello
379bbcdd14 feat: Improve zh-TW locale (#511) 2023-03-12 09:52:42 +08:00
Nothing1024
84a19aafc2 fix: 更新JSON导入检查 (#523) 2023-03-12 09:49:45 +08:00
ChenZhaoYu
cf03b65a4d chore: cover 2023-03-11 16:51:10 +08:00
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
47 changed files with 2990 additions and 280 deletions

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

View File

@@ -1,3 +1,67 @@
## 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
![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`

View File

@@ -1,28 +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 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/*
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 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/*
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"]

View File

@@ -174,6 +174,8 @@ pnpm dev
- `TIMEOUT_MS` timeout, in milliseconds, optional
- `SOCKS_PROXY_HOST` optional, effective with SOCKS_PROXY_PORT
- `SOCKS_PROXY_PORT` optional, effective with SOCKS_PROXY_HOST
- `HTTPS_PROXY` optional, support httphttps, socks5
- `ALL_PROXY` optional, support httphttps, socks5
![docker](./docs/docker.png)
@@ -223,6 +225,8 @@ services:
SOCKS_PROXY_HOST: xxxx
# socks proxy port, optional, effective with SOCKS_PROXY_HOST
SOCKS_PROXY_PORT: xxxx
# HTTPS Proxyoptional, support http, https, socks5
HTTPS_PROXY: http://xxx:7890
```
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`.
@@ -245,6 +249,8 @@ The `OPENAI_API_MODEL` is optional and only used when setting the `OPENAI_API_KE
| `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. |
| `HTTPS_PROXY` | Optional | HTTPS Proxy. |
| `ALL_PROXY` | Optional | ALL Proxy. |
> Note: Changing environment variables in Railway will cause re-deployment.

View File

@@ -24,6 +24,7 @@
- [测试环境运行](#测试环境运行)
- [后端服务](#后端服务)
- [前端网页](#前端网页)
- [环境变量](#环境变量)
- [打包](#打包)
- [使用 Docker](#使用-docker)
- [Docker 参数示例](#docker-参数示例)
@@ -51,7 +52,12 @@
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. 使用 `API` 时,如果网络不通,那是国内被墙了,你需要自建代理,绝对不要使用别人的公开代理,那是危险的。
3. 使用 `accessToken` 方式时反向代理将向第三方暴露您的访问令牌,这样做应该不会产生任何不良影响,但在使用这种方法之前请考虑风险。
4. 使用 `accessToken` 时,不管你是国内还是国外的机器,都会使用代理。默认代理为 [acheong08](https://github.com/acheong08) 大佬的 `https://bypass.duti.tech/api/conversation`,这不是后门也不是监听,除非你有能力自己翻过 `CF` 验证,用前请知悉。[社区代理](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy)(注意:只有这两个是推荐,其他第三方来源,请自行甄别)
5. 把项目发布到公共网络时,你应该设置 `AUTH_SECRET_KEY` 变量添加你的密码访问权限,你也应该修改 `index.html` 中的 `title`,防止被关键词搜索到。
切换方式:
1. 进入 `service/.env.example` 文件,复制内容到 `service/.env` 文件
@@ -59,21 +65,12 @@
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=
```
环境变量:
全部参数变量请查看或[这里](#docker-参数示例)
全部参数变量请查看或[这里](#环境变量)
```
/service/.env
/service/.env.example
```
## 待实现路线
@@ -99,7 +96,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
@@ -157,22 +154,34 @@ 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`
`ACCESS_TOKEN` 可用:
- `OPENAI_ACCESS_TOKEN``OPENAI_API_KEY` 二选一,同时存在时,`OPENAI_API_KEY` 优先
- `API_REVERSE_PROXY` 设置反向代理,可选,默认:`https://bypass.duti.tech/api/conversation`[社区](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy)(注意:只有这两个是推荐,其他第三方来源,请自行甄别)
通用:
- `AUTH_SECRET_KEY` 访问权限密钥,可选
- `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` 优先
- `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 一起时生效
![docker](./docs/docker.png)
#### Docker build & Run
@@ -221,6 +230,8 @@ services:
SOCKS_PROXY_HOST: xxxx
# Socks代理端口可选和 SOCKS_PROXY_HOST 一起时生效
SOCKS_PROXY_PORT: xxxx
# HTTPS 代理,可选,支持 httphttpssocks5
HTTPS_PROXY: http://xxxx:7890
```
- `OPENAI_API_BASE_URL` 可选,设置 `OPENAI_API_KEY` 时可用
- `OPENAI_API_MODEL` 可选,设置 `OPENAI_API_KEY` 时可用
@@ -242,6 +253,8 @@ services:
| `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代理端口 |
| `HTTPS_PROXY` | 可选 | HTTPS 代理,支持 httphttps, socks5 |
| `ALL_PROXY` | 可选 | 所有代理 代理,支持 httphttps, socks5 |
> 注意: `Railway` 修改环境变量会重新 `Deploy`

View File

@@ -24,14 +24,16 @@ services:
SOCKS_PROXY_HOST: xxxx
# Socks代理端口可选和 SOCKS_PROXY_HOST 一起时生效
SOCKS_PROXY_PORT: xxxx
# HTTPS_PROXY 代理,可选
HTTPS_PROXY: http://xxxx:7890
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

BIN
docs/c1-2.9.0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 282 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 282 KiB

After

Width:  |  Height:  |  Size: 96 KiB

BIN
docs/c2-2.9.0.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 78 KiB

View File

@@ -1,6 +1,6 @@
{
"name": "chatgpt-web",
"version": "2.10.2",
"version": "2.10.5",
"private": false,
"description": "ChatGPT Web",
"author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>",
@@ -58,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": {

1852
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

@@ -24,3 +24,6 @@ SOCKS_PROXY_HOST=
# Socks Proxy Port
SOCKS_PROXY_PORT=
# HTTPS PROXY
HTTPS_PROXY=

View File

@@ -11,7 +11,7 @@
"express"
],
"engines": {
"node": "^16 || ^18"
"node": "^16 || ^18 || ^19"
},
"scripts": {
"start": "esno ./src/index.ts",
@@ -24,10 +24,11 @@
"common:cleanup": "rimraf node_modules && rimraf pnpm-lock.yaml"
},
"dependencies": {
"chatgpt": "^5.0.8",
"chatgpt": "^5.0.10",
"dotenv": "^16.0.3",
"esno": "^0.16.3",
"express": "^4.18.2",
"https-proxy-agent": "^5.0.1",
"isomorphic-fetch": "^3.0.0",
"node-fetch": "^3.3.0",
"socks-proxy-agent": "^7.0.0"

20
service/pnpm-lock.yaml generated
View File

@@ -4,11 +4,12 @@ specifiers:
'@antfu/eslint-config': ^0.35.3
'@types/express': ^4.17.17
'@types/node': ^18.14.6
chatgpt: ^5.0.8
chatgpt: ^5.0.10
dotenv: ^16.0.3
eslint: ^8.35.0
esno: ^0.16.3
express: ^4.18.2
https-proxy-agent: ^5.0.1
isomorphic-fetch: ^3.0.0
node-fetch: ^3.3.0
rimraf: ^4.3.0
@@ -17,10 +18,11 @@ specifiers:
typescript: ^4.9.5
dependencies:
chatgpt: 5.0.8
chatgpt: 5.0.10
dotenv: 16.0.3
esno: 0.16.3
express: 4.18.2
https-proxy-agent: 5.0.1
isomorphic-fetch: 3.0.0
node-fetch: 3.3.0
socks-proxy-agent: 7.0.0
@@ -902,8 +904,8 @@ packages:
resolution: {integrity: sha512-mKKUkUbhPpQlCOfIuZkvSEgktjPFIsZKRRbC6KWVEMvlzblj3i3asQv5ODsrwt0N3pHAEvjP8KTQPHkp0+6jOg==}
dev: true
/chatgpt/5.0.8:
resolution: {integrity: sha512-Bjh7Y15QIsZ+SkQvbbZGymv1PGxkZ7X1vwqAwvyqaMMhbipU4kxht/GL62VCxhoUCXPwxTfScbFeNFtNldgqaw==}
/chatgpt/5.0.10:
resolution: {integrity: sha512-R3vtPlhCapFLkDXED0Cnt1DBcOZAXygr0M5U5kbSI0Fwm4uDQmc7qoIOnr17rd8eaa0JO/UDOevJdEWvd079qA==}
engines: {node: '>=14'}
hasBin: true
dependencies:
@@ -2079,6 +2081,16 @@ packages:
toidentifier: 1.0.1
dev: false
/https-proxy-agent/5.0.1:
resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}
engines: {node: '>= 6'}
dependencies:
agent-base: 6.0.2
debug: 4.3.4
transitivePeerDependencies:
- supports-color
dev: false
/human-signals/2.1.0:
resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==}
engines: {node: '>=10.17.0'}

View File

@@ -3,6 +3,7 @@ import 'isomorphic-fetch'
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 { sendResponse } from '../utils'
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
@@ -55,6 +56,14 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
}
}
const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.ALL_PROXY || process.env.all_proxy
if (httpsProxy) {
const agent = new HttpsProxyAgent(httpsProxy)
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}
api = new ChatGPTAPI({ ...options })
apiModel = 'ChatGPTAPI'
}
@@ -74,6 +83,14 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
}
}
const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.ALL_PROXY || process.env.all_proxy
if (httpsProxy) {
const agent = new HttpsProxyAgent(httpsProxy)
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}
if (process.env.API_REVERSE_PROXY)
options.apiReverseProxyUrl = process.env.API_REVERSE_PROXY
@@ -87,8 +104,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 }
@@ -119,6 +136,8 @@ async function chatReplyProcess(
}
async function chatConfig() {
const httpsProxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.ALL_PROXY || process.env.all_proxy
return sendResponse({
type: 'Success',
data: {
@@ -126,6 +145,7 @@ async function chatConfig() {
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}`) : '-',
httpsProxy,
} as ModelConfig,
})
}

View File

@@ -11,7 +11,7 @@ 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()
})

View File

@@ -19,6 +19,7 @@ export interface ModelConfig {
reverseProxy?: string
timeoutMs?: number
socksProxy?: string
httpsProxy?: string
}
export type ApiModel = 'ChatGPTAPI' | 'ChatGPTUnofficialProxyAPI' | undefined

14
src/assets/recommend.json Normal file
View File

@@ -0,0 +1,14 @@
[
{
"key": "chatgpt-prompt-collection",
"desc": "Nothing1024收集整理的prompts",
"downloadUrl": "https://raw.githubusercontent.com/Nothing1024/chatgpt-prompt-collection/main/awesome-chatgpt-prompts-zh.json",
"url": "https://github.com/Nothing1024/chatgpt-prompt-collection"
},
{
"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"
}
]

View File

@@ -0,0 +1,463 @@
<script setup lang='ts'>
import type { DataTableColumns } from 'naive-ui'
import { computed, h, ref, watch } from 'vue'
import { NButton, NCard, NDataTable, NDivider, 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'
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: 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(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('')
}
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('')
}
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 = () => {
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'))
changeShowModal('')
}
catch {
message.error('JSON 格式错误,请检查 JSON 格式')
changeShowModal('')
}
}
// 模板导出
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
await fetch(downloadURL.value)
.then(response => response.json())
.then((jsonData) => {
tempPromptValue.value = JSON.stringify(jsonData)
}).then(() => {
importPromptTemplate()
})
downloadURL.value = ''
}
catch {
message.error(t('store.downloadError'))
}
finally {
importLoading.value = false
}
}
// 移动端自适应相关
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: 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>
<NMessageProvider>
<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"
: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>
<br>
<NDataTable
:max-height="400"
:columns="columns"
:data="dataSource"
:pagination="pagination"
:bordered="false"
/>
</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 />
<NLayoutContent
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"
>
<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>
</NLayoutContent>
</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() }"
>
{{ t('common.import') }}
</NButton>
</NSpace>
</NModal>
</NMessageProvider>
</template>

View File

@@ -9,6 +9,7 @@ interface ConfigState {
reverseProxy?: string
apiModel?: string
socksProxy?: string
httpsProxy?: string
}
const loading = ref(false)
@@ -57,6 +58,7 @@ onMounted(() => {
<p>{{ $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>

View File

@@ -1,16 +1,19 @@
<script lang="ts" setup>
import { computed, ref } from 'vue'
import { NButton, NInput, NPopconfirm, 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'
const appStore = useAppStore()
const userStore = useUserStore()
const { isMobile } = useBasicLayout()
const ms = useMessage()
const theme = computed(() => appStore.theme)
@@ -148,7 +151,10 @@ function handleImportButtonClick(): void {
</NButton>
</div>
<div class="flex items-center space-x-4">
<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">
@@ -199,15 +205,12 @@ function handleImportButtonClick(): void {
<div class="flex items-center space-x-4">
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.language') }}</span>
<div class="flex flex-wrap items-center gap-4">
<template v-for="item of languageOptions" :key="item.key">
<NButton
size="small"
:type="item.key === language ? 'primary' : undefined"
@click="appStore.setLanguage(item.key)"
>
{{ item.label }}
</NButton>
</template>
<NSelect
style="width: 140px"
:value="language"
:options="languageOptions"
@update-value="value => appStore.setLanguage(value)"
/>
</div>
</div>
<div class="flex items-center space-x-4">

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'
@@ -30,8 +30,8 @@ const show = computed({
</script>
<template>
<NModal v-model:show="show" :auto-focus="false">
<NCard role="dialog" aria-modal="true" :bordered="false" style="width: 95%; 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>
@@ -50,6 +50,6 @@ const show = computed({
<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,13 +1,25 @@
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',
@@ -50,6 +62,23 @@ export default {
reverseProxy: 'Reverse Proxy',
timeout: 'Timeout',
socks: 'Socks',
httpsProxy: 'HTTPS Proxy',
},
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',
},
}

View File

@@ -21,9 +21,7 @@ const i18n = createI18n({
},
})
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

View File

@@ -1,13 +1,25 @@
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: '操作成功',
@@ -50,6 +62,23 @@ export default {
reverseProxy: '反向代理',
timeout: '超时',
socks: 'Socks',
httpsProxy: 'HTTPS Proxy',
},
store: {
local: '本地',
online: '在线',
title: '标题',
description: '描述',
clearStoreConfirm: '是否清空数据?',
importPlaceholder: '请粘贴 JSON 数据到此处',
addRepeatTitleTips: '标题重复,请重新输入',
addRepeatContentTips: '内容重复:{msg},请重新输入',
editRepeatTitleTips: '标题冲突,请重新修改',
editRepeatContentTips: '内容冲突{msg} ,请重新修改',
importError: '键值不匹配',
importRepeatTitle: '标题重复跳过:{msg}',
importRepeatContent: '内容重复跳过:{msg}',
onlineImportWarning: '注意:请检查 JSON 文件来源!',
downloadError: '请检查网络状态与 JSON 文件有效性',
},
}

View File

@@ -1,15 +1,27 @@
export default {
common: {
add: '新增',
addSuccess: '新增成功',
edit: '編輯',
editSuccess: '編輯成功',
delete: '刪除',
deleteSuccess: '刪除成功',
save: '儲存',
saveSuccess: '儲存成功',
reset: '重設',
action: '操作',
export: '匯出',
exportSuccess: '匯出成功',
import: '匯入',
importSuccess: '匯入成功',
clear: '清除',
clearSuccess: '清除成功',
yes: '是',
no: '否',
noData: '暫無資料',
wrong: '好像出錯了,請稍後再試。',
confirm: '確認',
download: '下載',
noData: '目前無資料',
wrong: '發生錯誤,請稍後再試。',
success: '操作成功',
failed: '操作失敗',
verify: '驗證',
@@ -28,11 +40,12 @@ export default {
exportSuccess: '儲存成功',
exportFailed: '儲存失敗',
usingContext: '上下文模式',
turnOnContext: '在當前模式下, 發送訊息會攜帶之前的聊天記錄。',
turnOffContext: '在當前模式下, 發送訊息不會攜帶之前的聊天記錄。',
turnOnContext: '啟用上下文模式,在此模式下發送訊息會包含之前的聊天記錄。',
turnOffContext: '關閉上下文模式,在此模式下發送訊息不會包含之前的聊天記錄。',
deleteMessage: '刪除訊息',
deleteMessageConfirm: '是否刪除此訊息?',
deleteHistoryConfirm: '確定刪除此紀錄?',
clearHistoryConfirm: '確定清除紀錄?',
},
setting: {
setting: '設定',
@@ -49,5 +62,23 @@ export default {
reverseProxy: '反向代理',
timeout: '逾時',
socks: 'Socks',
httpsProxy: 'HTTPS Proxy',
},
store: {
local: '本機',
online: '線上',
title: '標題',
description: '描述',
clearStoreConfirm: '是否清除資料?',
importPlaceholder: '請將 JSON 資料貼在此處',
addRepeatTitleTips: '標題重複,請重新輸入',
addRepeatContentTips: '內容重複:{msg},請重新輸入',
editRepeatTitleTips: '標題衝突,請重新修改',
editRepeatContentTips: '內容衝突{msg} ,請重新修改',
importError: '鍵值不符合',
importRepeatTitle: '因標題重複跳過:{msg}',
importRepeatContent: '因內容重複跳過:{msg}',
onlineImportWarning: '注意:請檢查 JSON 檔案來源!',
downloadError: '請檢查網路狀態與 JSON 檔案有效性',
},
}

View File

@@ -1,4 +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,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

@@ -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,20 +1,25 @@
<script setup lang='ts'>
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { NButton, NInput, useDialog, useMessage } 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()
@@ -22,9 +27,11 @@ 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 }
@@ -33,15 +40,18 @@ const conversationList = computed(() => dataSources.value.filter(item => (!item.
const prompt = ref<string>('')
const loading = ref<boolean>(false)
const usingContext = ref<boolean>(true)
const actionVisible = ref<boolean>(true)
// 添加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
@@ -88,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')
@@ -181,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 = {}
@@ -205,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') {
@@ -366,22 +400,29 @@ function handleStop() {
}
}
function toggleUsingContext() {
usingContext.value = !usingContext.value
if (usingContext.value)
ms.success(t('chat.turnOnContext'))
else
ms.warning(t('chat.turnOffContext'))
}
function onInputFocus() {
if (isMobile.value)
actionVisible.value = false
}
function onInputBlur() {
if (isMobile.value)
actionVisible.value = true
// 可优化部分
// 搜索选项计算这里使用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(() => {
@@ -394,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', 'overflow-hidden']
classes = ['sticky', 'left-0', 'bottom-0', 'right-0', 'p-2', 'pr-3', 'overflow-hidden']
return classes
})
@@ -418,7 +453,13 @@ 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"
@@ -465,32 +506,35 @@ onUnmounted(() => {
<footer :class="footerClass">
<div class="w-full max-w-screen-xl m-auto">
<div class="flex items-center justify-between space-x-2">
<div v-if="actionVisible" class="flex items-center space-x-2">
<HoverButton @click="handleClear">
<span class="text-xl text-[#4f555e] dark:text-white">
<SvgIcon icon="ri:delete-bin-line" />
</span>
</HoverButton>
<HoverButton @click="handleExport">
<span class="text-xl text-[#4f555e] dark:text-white">
<SvgIcon icon="ri:download-2-line" />
</span>
</HoverButton>
<HoverButton @click="toggleUsingContext">
<span class="text-xl" :class="{ 'text-[#4b9e5f]': usingContext, 'text-[#a8071a]': !usingContext }">
<SvgIcon icon="ri:chat-history-line" />
</span>
</HoverButton>
</div>
<NInput
v-model:value="prompt"
type="textarea"
:autosize="{ minRows: 1, maxRows: 2 }"
:placeholder="placeholder"
@focus="onInputFocus"
@blur="onInputBlur"
@keypress="handleEnter"
/>
<HoverButton @click="handleClear">
<span class="text-xl text-[#4f555e] dark:text-white">
<SvgIcon icon="ri:delete-bin-line" />
</span>
</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
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">

View File

@@ -3,7 +3,6 @@ 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, useAuthStore, useChatStore } from '@/store'
@@ -40,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" />

View File

@@ -64,8 +64,7 @@ function handlePress(event: KeyboardEvent) {
</p>
<Icon403 class="w-[200px] m-auto" />
</header>
<NInput v-model:value="token" type="text" placeholder="" @keypress="handlePress" />
<NInput v-model:value="token" type="password" placeholder="" @keypress="handlePress" />
<NButton
block
type="primary"

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