Merge branch 'Chanzhaoyu:main' into patch-1

This commit is contained in:
MuChangQiu 2023-04-04 14:50:26 +08:00 committed by GitHub
commit 1a7c580ea2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 1501 additions and 1559 deletions

View File

@ -4,3 +4,4 @@ node_modules
Dockerfile Dockerfile
.* .*
*/.* */.*
!.env

2
.env
View File

@ -1,7 +1,7 @@
# Glob API URL # Glob API URL
VITE_GLOB_API_URL=/api VITE_GLOB_API_URL=/api
VITE_APP_API_BASE_URL=http://localhost:3002/ VITE_APP_API_BASE_URL=http://127.0.0.1:3002/
# Whether long replies are supported, which may result in higher API fees # Whether long replies are supported, which may result in higher API fees
VITE_GLOB_OPEN_LONG_REPLY=false VITE_GLOB_OPEN_LONG_REPLY=false

2
.eslintignore Normal file
View File

@ -0,0 +1,2 @@
docker-compose
kubernetes

22
.github/workflows/issues_close.yml vendored Normal file
View File

@ -0,0 +1,22 @@
name: Close inactive issues
on:
schedule:
- cron: '30 1 * * *'
jobs:
close-issues:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v5
with:
days-before-issue-stale: 10
days-before-issue-close: 5
stale-issue-label: stale
stale-issue-message: This issue is stale because it has been open for 10 days with no activity.
close-issue-message: This issue was closed because it has been inactive for 5 days since being marked as stale.
days-before-pr-stale: -1
days-before-pr-close: -1
repo-token: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,3 +1,33 @@
## v2.10.9
`2023-04-03`
> 更新默认 `accessToken` 反代地址为 [[acheong08](https://github.com/acheong08)] 的 `https://bypass.churchless.tech/api/conversation`
## Enhancement
- 添加 `socks5` 代理认证 [[yimiaoxiehou](https://github.com/Chanzhaoyu/chatgpt-web/pull/999)]
- 添加 `socks` 代理用户名密码的配置 [[hank-cp](https://github.com/Chanzhaoyu/chatgpt-web/pull/890)]
- 添加可选日志打印 [[zcong1993](https://github.com/Chanzhaoyu/chatgpt-web/pull/1041)]
- 更新侧边栏按钮本地化[[simonwu53](https://github.com/Chanzhaoyu/chatgpt-web/pull/911)]
- 优化代码块滚动条高度 [[Fog3211](https://github.com/Chanzhaoyu/chatgpt-web/pull/1153)]
## BugFix
- 修复 `PWA` 问题 [[bingo235](https://github.com/Chanzhaoyu/chatgpt-web/pull/807)]
- 修复 `ESM` 错误 [[kidonng](https://github.com/Chanzhaoyu/chatgpt-web/pull/826)]
- 修复反向代理开启时限流失效的问题 [[gitgitgogogo](https://github.com/Chanzhaoyu/chatgpt-web/pull/863)]
- 修复 `docker` 构建时 `.env` 可能被忽略的问题 [[zaiMoe](https://github.com/Chanzhaoyu/chatgpt-web/pull/877)]
- 修复导出异常错误 [[KingTwinkle](https://github.com/Chanzhaoyu/chatgpt-web/pull/938)]
- 修复空值异常 [[vchenpeng](https://github.com/Chanzhaoyu/chatgpt-web/pull/1103)]
- 移动端上的体验问题
## Other
- `Docker` 容器名字名义 [[LOVECHEN](https://github.com/Chanzhaoyu/chatgpt-web/pull/1035)]
- `kubernetes` 部署配置 [[CaoYunzhou](https://github.com/Chanzhaoyu/chatgpt-web/pull/1001)]
- 感谢 [[assassinliujie](https://github.com/Chanzhaoyu/chatgpt-web/pull/962)] 和 [[puppywang](https://github.com/Chanzhaoyu/chatgpt-web/pull/1017)] 的某些贡献
- 更新 `kubernetes/deploy.yaml` [[idawnwon](https://github.com/Chanzhaoyu/chatgpt-web/pull/1085)]
- 文档更新 [[#yi-ge](https://github.com/Chanzhaoyu/chatgpt-web/pull/883)]
- 文档更新 [[weifeng12x](https://github.com/Chanzhaoyu/chatgpt-web/pull/880)]
- 依赖更新
## v2.10.8 ## v2.10.8
`2023-03-23` `2023-03-23`

View File

@ -1,333 +0,0 @@
# ChatGPT Web
<div style="font-size: 1.5rem;">
<a href="./README.md">中文</a> |
<a href="./README.en.md">English</a>
</div>
</br>
> Disclaimer: This project is only released on GitHub, under the MIT License, free and for open-source learning purposes. There will be no account selling, paid services, discussion groups, or forums. Beware of fraud.
![cover](./docs/c1.png)
![cover2](./docs/c2.png)
- [ChatGPT Web](#chatgpt-web)
- [Introduction](#introduction)
- [Roadmap](#roadmap)
- [Prerequisites](#prerequisites)
- [Node](#node)
- [PNPM](#pnpm)
- [Fill in the Keys](#fill-in-the-keys)
- [Install Dependencies](#install-dependencies)
- [Backend](#backend)
- [Frontend](#frontend)
- [Run in Test Environment](#run-in-test-environment)
- [Backend Service](#backend-service)
- [Frontend Webpage](#frontend-webpage)
- [Packaging](#packaging)
- [Using Docker](#using-docker)
- [Docker Parameter Example](#docker-parameter-example)
- [Docker Build \& Run](#docker-build--run)
- [Docker Compose](#docker-compose)
- [Deployment with Railway](#deployment-with-railway)
- [Railway Environment Variables](#railway-environment-variables)
- [Manual packaging](#manual-packaging)
- [Backend service](#backend-service-1)
- [Frontend webpage](#frontend-webpage-1)
- [Frequently Asked Questions](#frequently-asked-questions)
- [Contributing](#contributing)
- [Sponsorship](#sponsorship)
- [License](#license)
## Introduction
Supports dual models, provides two unofficial `ChatGPT API` methods:
| Method | Free? | Reliability | Quality |
| --------------------------------------------- | ------ | ----------- | ------- |
| `ChatGPTAPI(gpt-3.5-turbo-0301)` | No | Reliable | Relatively clumsy |
| `ChatGPTUnofficialProxyAPI(Web accessToken)` | Yes | Relatively unreliable | Smart |
Comparison:
1. `ChatGPTAPI` uses `gpt-3.5-turbo-0301` to simulate `ChatGPT` through the official `OpenAI` completion `API` (the most reliable method, but it is not free and does not use models specifically tuned for chat).
2. `ChatGPTUnofficialProxyAPI` accesses `ChatGPT`'s backend `API` via an unofficial proxy server to bypass `Cloudflare` (uses the real `ChatGPT`, is very lightweight, but depends on third-party servers and has rate limits).
[Details](https://github.com/Chanzhaoyu/chatgpt-web/issues/138)
Switching Methods:
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.
Reverse Proxy:
Available when using `ChatGPTUnofficialProxyAPI`.[Details](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy)
```shell
# service/.env
API_REVERSE_PROXY=
```
Environment Variables:
For all parameter variables, check [here](#docker-parameter-example) or see:
```
/service/.env
```
## Roadmap
[✓] Dual models
[✓] Multiple session storage and context logic
[✓] Formatting and beautifying code-like message types
[✓] Access rights control
[✓] Data import and export
[✓] Save message to local image
[✓] Multilingual interface
[✓] Interface themes
[✗] More...
## Prerequisites
### Node
`node` requires version `^16 || ^18` (`node >= 14` requires installation of [fetch polyfill](https://github.com/developit/unfetch#usage-as-a-polyfill)), and multiple local `node` versions can be managed using [nvm](https://github.com/nvm-sh/nvm).
```shell
node -v
```
### PNPM
If you have not installed `pnpm` before:
```shell
npm install pnpm -g
```
### Fill in the Keys
Get `Openai Api Key` or `accessToken` and fill in the local environment variables [jump](#introduction)
```
# service/.env file
# OpenAI API Key - https://platform.openai.com/overview
OPENAI_API_KEY=
# change this to an `accessToken` extracted from the ChatGPT site's `https://chat.openai.com/api/auth/session` response
OPENAI_ACCESS_TOKEN=
```
## Install Dependencies
> To make it easier for `backend developers` to understand, we did not use the front-end `workspace` mode, but stored it in different folders. If you only need to do secondary development of the front-end page, delete the `service` folder.
### Backend
Enter the `/service` folder and run the following command
```shell
pnpm install
```
### Frontend
Run the following command in the root directory
```shell
pnpm bootstrap
```
## Run in Test Environment
### Backend Service
Enter the `/service` folder and run the following command
```shell
pnpm start
```
### Frontend Webpage
Run the following command in the root directory
```shell
pnpm dev
```
## Packaging
### Using Docker
#### Docker Parameter Example
- `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
- `HTTPS_PROXY` optional, support httphttps, socks5
- `ALL_PROXY` optional, support httphttps, socks5
![docker](./docs/docker.png)
#### Docker Build & Run
```bash
docker build -t chatgpt-web .
# foreground operation
docker run --name chatgpt-web --rm -it -p 127.0.0.1:3002:3002 --env OPENAI_API_KEY=your_api_key chatgpt-web
# background operation
docker run --name chatgpt-web -d -p 127.0.0.1:3002:3002 --env OPENAI_API_KEY=your_api_key chatgpt-web
# running address
http://localhost:3002/
```
#### Docker Compose
[Hub Address](https://hub.docker.com/repository/docker/chenzhaoyu94/chatgpt-web/general)
```yml
version: '3'
services:
app:
image: chenzhaoyu94/chatgpt-web # always use latest, pull the tag image again when updating
ports:
- 127.0.0.1:3002:3002
environment:
# one of two
OPENAI_API_KEY: xxxxxx
# one of two
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
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`.
### Deployment with Railway
[![Deploy on Railway](https://railway.app/button.svg)](https://railway.app/new/template/yytmgc)
#### Railway Environment Variables
| Environment Variable | Required | Description |
| -------------------- | -------- | ------------------------------------------------------------------------------------------------- |
| `PORT` | Required | Default: `3002` |
| `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. |
| `HTTPS_PROXY` | Optional | HTTPS Proxy. |
| `ALL_PROXY` | Optional | ALL Proxy. |
> Note: Changing environment variables in Railway will cause re-deployment.
### Manual packaging
#### Backend service
> If you don't need the `node` interface of this project, you can skip the following steps.
Copy the `service` folder to a server that has a `node` service environment.
```shell
# Install
pnpm install
# Build
pnpm build
# Run
pnpm prod
```
PS: You can also run `pnpm start` directly on the server without packaging.
#### Frontend webpage
1. Refer to the root directory `.env.example` file content to create `.env` file, modify `VITE_GLOB_API_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)
```shell
pnpm build
```
## Frequently Asked Questions
Q: Why does Git always report an error when committing?
A: Because there is submission information verification, please follow the [Commit Guidelines](./CONTRIBUTING.en.md).
Q: Where to change the request interface if only the frontend page is used?
A: The `VITE_GLOB_API_URL` field in the `.env` file at the root directory.
Q: All red when saving the file?
A: For `vscode`, please install the recommended plug-in of the project or manually install the `Eslint` plug-in.
Q: Why doesn't the frontend have a typewriter effect?
A: One possible reason is that after Nginx reverse proxying, buffering is turned on, and Nginx will try to buffer a certain amount of data from the backend before sending it to the browser. Please try adding `proxy_buffering off;` after the reverse proxy parameter and then reloading Nginx. Other web server configurations are similar.
## Contributing
Please read the [Contributing Guidelines](./CONTRIBUTING.en.md) before contributing.
Thanks to all the contributors!
<a href="https://github.com/Chanzhaoyu/chatgpt-web/graphs/contributors">
<img src="https://contrib.rocks/image?repo=Chanzhaoyu/chatgpt-web" />
</a>
## Sponsorship
If you find this project helpful and circumstances permit, you can give me a little support. Thank you very much for your support~
<div style="display: flex; gap: 20px;">
<div style="text-align: center">
<img style="max-width: 100%" src="./docs/wechat.png" alt="WeChat" />
<p>WeChat Pay</p>
</div>
<div style="text-align: center">
<img style="max-width: 100%" src="./docs/alipay.png" alt="Alipay" />
<p>Alipay</p>
</div>
</div>
## License
MIT © [ChenZhaoYu](./license)

View File

@ -1,11 +1,5 @@
# ChatGPT Web # ChatGPT Web
<div style="font-size: 1.5rem;">
<a href="./README.md">中文</a> |
<a href="./README.en.md">English</a>
</div>
</br>
> 声明:此项目只发布于 Github基于 MIT 协议,免费且作为开源学习使用。并且不会有任何形式的卖号、付费服务、讨论群、讨论组等行为。谨防受骗。 > 声明:此项目只发布于 Github基于 MIT 协议,免费且作为开源学习使用。并且不会有任何形式的卖号、付费服务、讨论群、讨论组等行为。谨防受骗。
![cover](./docs/c1.png) ![cover](./docs/c1.png)
@ -49,14 +43,14 @@
| `ChatGPTUnofficialProxyAPI(网页 accessToken)` | 是 | 相对不可靠 | 聪明 | | `ChatGPTUnofficialProxyAPI(网页 accessToken)` | 是 | 相对不可靠 | 聪明 |
对比: 对比:
1. `ChatGPTAPI` 使用 `gpt-3.5-turbo-0301` 通过官方`OpenAI`补全`API`模拟`ChatGPT`(最稳健的方法,但它不是免费的,并且没有使用针对聊天进行微调的模型) 1. `ChatGPTAPI` 使用 `gpt-3.5-turbo` 通过 `OpenAI` 官方 `API` 调用 `ChatGPT`
2. `ChatGPTUnofficialProxyAPI` 使用非官方代理服务器访问 `ChatGPT` 的后端`API`,绕过`Cloudflare`使用真实的的`ChatGPT`,非常轻量级,但依赖于第三方服务器,并且有速率限制) 2. `ChatGPTUnofficialProxyAPI` 使用非官方代理服务器访问 `ChatGPT` 的后端`API`,绕过`Cloudflare`(依赖于第三方服务器,并且有速率限制)
警告: 警告:
1. 你应该首先使用 `API` 方式 1. 你应该首先使用 `API` 方式
2. 使用 `API` 时,如果网络不通,那是国内被墙了,你需要自建代理,绝对不要使用别人的公开代理,那是危险的。 2. 使用 `API` 时,如果网络不通,那是国内被墙了,你需要自建代理,绝对不要使用别人的公开代理,那是危险的。
3. 使用 `accessToken` 方式时反向代理将向第三方暴露您的访问令牌,这样做应该不会产生任何不良影响,但在使用这种方法之前请考虑风险。 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)(注意:只有这两个是推荐,其他第三方来源,请自行甄别) 4. 使用 `accessToken` 时,不管你是国内还是国外的机器,都会使用代理。默认代理为 [acheong08](https://github.com/acheong08) 大佬的 `https://bypass.churchless.tech/api/conversation`,这不是后门也不是监听,除非你有能力自己翻过 `CF` 验证,用前请知悉。[社区代理](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy)(注意:只有这两个是推荐,其他第三方来源,请自行甄别)
5. 把项目发布到公共网络时,你应该设置 `AUTH_SECRET_KEY` 变量添加你的密码访问权限,你也应该修改 `index.html` 中的 `title`,防止被关键词搜索到。 5. 把项目发布到公共网络时,你应该设置 `AUTH_SECRET_KEY` 变量添加你的密码访问权限,你也应该修改 `index.html` 中的 `title`,防止被关键词搜索到。
切换方式: 切换方式:
@ -161,11 +155,12 @@ pnpm dev
- `OPENAI_API_KEY``OPENAI_ACCESS_TOKEN` 二选一 - `OPENAI_API_KEY``OPENAI_ACCESS_TOKEN` 二选一
- `OPENAI_API_MODEL` 设置模型,可选,默认:`gpt-3.5-turbo` - `OPENAI_API_MODEL` 设置模型,可选,默认:`gpt-3.5-turbo`
- `OPENAI_API_BASE_URL` 设置接口地址,可选,默认:`https://api.openai.com` - `OPENAI_API_BASE_URL` 设置接口地址,可选,默认:`https://api.openai.com`
- `OPENAI_API_DISABLE_DEBUG` 设置接口关闭 debug 日志可选默认empty 不关闭
`ACCESS_TOKEN` 可用: `ACCESS_TOKEN` 可用:
- `OPENAI_ACCESS_TOKEN``OPENAI_API_KEY` 二选一,同时存在时,`OPENAI_API_KEY` 优先 - `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)(注意:只有这两个是推荐,其他第三方来源,请自行甄别) - `API_REVERSE_PROXY` 设置反向代理,可选,默认:`https://bypass.churchless.tech/api/conversation`[社区](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy)(注意:只有这两个是推荐,其他第三方来源,请自行甄别)
通用: 通用:
@ -219,7 +214,8 @@ services:
OPENAI_ACCESS_TOKEN: xxx OPENAI_ACCESS_TOKEN: xxx
# API接口地址可选设置 OPENAI_API_KEY 时可用 # API接口地址可选设置 OPENAI_API_KEY 时可用
OPENAI_API_BASE_URL: xxx OPENAI_API_BASE_URL: xxx
# API模型可选设置 OPENAI_API_KEY 时可用 # API模型可选设置 OPENAI_API_KEY 时可用https://platform.openai.com/docs/models
# gpt-4, gpt-4-0314, gpt-4-32k, gpt-4-32k-0314, gpt-3.5-turbo, gpt-3.5-turbo-0301, text-davinci-003, text-davinci-002, code-davinci-002
OPENAI_API_MODEL: xxx OPENAI_API_MODEL: xxx
# 反向代理,可选 # 反向代理,可选
API_REVERSE_PROXY: xxx API_REVERSE_PROXY: xxx
@ -257,6 +253,8 @@ services:
| `API_REVERSE_PROXY` | 可选,`Web API` 时可用 | `Web API` 反向代理地址 [详情](https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy) | | `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_HOST` | 可选,和 `SOCKS_PROXY_PORT` 一起时生效 | Socks代理 |
| `SOCKS_PROXY_PORT` | 可选,和 `SOCKS_PROXY_HOST` 一起时生效 | Socks代理端口 | | `SOCKS_PROXY_PORT` | 可选,和 `SOCKS_PROXY_HOST` 一起时生效 | Socks代理端口 |
| `SOCKS_PROXY_USERNAME` | 可选,和 `SOCKS_PROXY_HOST` 一起时生效 | Socks代理用户名 |
| `SOCKS_PROXY_PASSWORD` | 可选,和 `SOCKS_PROXY_HOST` 一起时生效 | Socks代理密码 |
| `HTTPS_PROXY` | 可选 | HTTPS 代理,支持 httphttps, socks5 | | `HTTPS_PROXY` | 可选 | HTTPS 代理,支持 httphttps, socks5 |
| `ALL_PROXY` | 可选 | 所有代理 代理,支持 httphttps, socks5 | | `ALL_PROXY` | 可选 | 所有代理 代理,支持 httphttps, socks5 |

View File

@ -2,33 +2,39 @@ version: '3'
services: services:
app: app:
container_name: chatgpt-web
image: chenzhaoyu94/chatgpt-web # 总是使用latest,更新时重新pull该tag镜像即可 image: chenzhaoyu94/chatgpt-web # 总是使用latest,更新时重新pull该tag镜像即可
ports: ports:
- 3002:3002 - 3002:3002
environment: environment:
# 二选一 # 二选一
OPENAI_API_KEY: sk-xxx OPENAI_API_KEY:
# 二选一 # 二选一
OPENAI_ACCESS_TOKEN: xxx OPENAI_ACCESS_TOKEN:
# API接口地址可选设置 OPENAI_API_KEY 时可用 # API接口地址可选设置 OPENAI_API_KEY 时可用
OPENAI_API_BASE_URL: xxx OPENAI_API_BASE_URL:
# API模型可选设置 OPENAI_API_KEY 时可用 # API模型可选设置 OPENAI_API_KEY 时可用
OPENAI_API_MODEL: xxx OPENAI_API_MODEL:
# 反向代理,可选 # 反向代理,可选
API_REVERSE_PROXY: xxx API_REVERSE_PROXY:
# 访问权限密钥,可选 # 访问权限密钥,可选
AUTH_SECRET_KEY: xxx AUTH_SECRET_KEY:
# 每小时最大请求次数,可选,默认无限 # 每小时最大请求次数,可选,默认无限
MAX_REQUEST_PER_HOUR: 0 MAX_REQUEST_PER_HOUR: 0
# 超时,单位毫秒,可选 # 超时,单位毫秒,可选
TIMEOUT_MS: 60000 TIMEOUT_MS: 60000
# Socks代理可选和 SOCKS_PROXY_PORT 一起时生效 # Socks代理可选和 SOCKS_PROXY_PORT 一起时生效
SOCKS_PROXY_HOST: xxx SOCKS_PROXY_HOST:
# Socks代理端口可选和 SOCKS_PROXY_HOST 一起时生效 # Socks代理端口可选和 SOCKS_PROXY_HOST 一起时生效
SOCKS_PROXY_PORT: xxx SOCKS_PROXY_PORT:
# Socks代理用户名可选和 SOCKS_PROXY_HOST & SOCKS_PROXY_PORT 一起时生效
SOCKS_PROXY_USERNAME:
# Socks代理密码可选和 SOCKS_PROXY_HOST & SOCKS_PROXY_PORT 一起时生效
SOCKS_PROXY_PASSWORD:
# HTTPS_PROXY 代理,可选 # HTTPS_PROXY 代理,可选
HTTPS_PROXY: http://xxx:7890 HTTPS_PROXY:
nginx: nginx:
container_name: nginx
image: nginx:alpine image: nginx:alpine
ports: ports:
- '80:80' - '80:80'

9
kubernetes/README.md Normal file
View File

@ -0,0 +1,9 @@
## 增加一个Kubernetes的部署方式
```
kubectl apply -f deploy.yaml
```
### 如果需要Ingress域名接入
```
kubectl apply -f ingress.yaml
```

66
kubernetes/deploy.yaml Normal file
View File

@ -0,0 +1,66 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: chatgpt-web
labels:
app: chatgpt-web
spec:
replicas: 1
selector:
matchLabels:
app: chatgpt-web
strategy:
type: RollingUpdate
template:
metadata:
labels:
app: chatgpt-web
spec:
containers:
- image: chenzhaoyu94/chatgpt-web
name: chatgpt-web
imagePullPolicy: Always
ports:
- containerPort: 3002
env:
- name: OPENAI_API_KEY
value: sk-xxx
- name: OPENAI_API_BASE_URL
value: 'https://api.openai.com'
- name: OPENAI_API_MODEL
value: gpt-3.5-turbo
- name: API_REVERSE_PROXY
value: https://bypass.churchless.tech/api/conversation
- name: AUTH_SECRET_KEY
value: '123456'
- name: TIMEOUT_MS
value: '60000'
- name: SOCKS_PROXY_HOST
value: ''
- name: SOCKS_PROXY_PORT
value: ''
- name: HTTPS_PROXY
value: ''
resources:
limits:
cpu: 500m
memory: 500Mi
requests:
cpu: 300m
memory: 300Mi
---
apiVersion: v1
kind: Service
metadata:
labels:
app: chatgpt-web
name: chatgpt-web
spec:
ports:
- name: chatgpt-web
port: 3002
protocol: TCP
targetPort: 3002
selector:
app: chatgpt-web
type: ClusterIP

21
kubernetes/ingress.yaml Normal file
View File

@ -0,0 +1,21 @@
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/proxy-connect-timeout: '5'
name: chatgpt-web
spec:
rules:
- host: chatgpt.example.com
http:
paths:
- backend:
service:
name: chatgpt-web
port:
number: 3002
path: /
pathType: ImplementationSpecific
tls:
- secretName: chatgpt-web-tls

View File

@ -1,6 +1,6 @@
{ {
"name": "chatgpt-web", "name": "chatgpt-web",
"version": "2.10.8", "version": "2.10.9",
"private": false, "private": false,
"description": "ChatGPT Web", "description": "ChatGPT Web",
"author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>", "author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>",

File diff suppressed because it is too large Load Diff

View File

@ -10,7 +10,12 @@ OPENAI_API_BASE_URL=
# OpenAI API Model - https://platform.openai.com/docs/models # OpenAI API Model - https://platform.openai.com/docs/models
OPENAI_API_MODEL= OPENAI_API_MODEL=
# Reverse Proxy # set `true` to disable OpenAI API debug log
OPENAI_API_DISABLE_DEBUG=
# Reverse Proxy - Available on accessToken
# Default: https://bypass.churchless.tech/api/conversation
# More: https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy
API_REVERSE_PROXY= API_REVERSE_PROXY=
# timeout # timeout
@ -28,6 +33,12 @@ SOCKS_PROXY_HOST=
# Socks Proxy Port # Socks Proxy Port
SOCKS_PROXY_PORT= SOCKS_PROXY_PORT=
# Socks Proxy Username
SOCKS_PROXY_USERNAME=
# Socks Proxy Password
SOCKS_PROXY_PASSWORD=
# HTTPS PROXY # HTTPS PROXY
HTTPS_PROXY= HTTPS_PROXY=

View File

@ -16,7 +16,7 @@
"scripts": { "scripts": {
"start": "esno ./src/index.ts", "start": "esno ./src/index.ts",
"dev": "esno watch ./src/index.ts", "dev": "esno watch ./src/index.ts",
"prod": "esno ./build/index.js", "prod": "node ./build/index.mjs",
"build": "pnpm clean && tsup", "build": "pnpm clean && tsup",
"clean": "rimraf build", "clean": "rimraf build",
"lint": "eslint .", "lint": "eslint .",

View File

@ -3,13 +3,14 @@ import 'isomorphic-fetch'
import type { ChatGPTAPIOptions, ChatMessage, SendMessageOptions } from 'chatgpt' import type { ChatGPTAPIOptions, ChatMessage, SendMessageOptions } from 'chatgpt'
import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt' import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt'
import { SocksProxyAgent } from 'socks-proxy-agent' import { SocksProxyAgent } from 'socks-proxy-agent'
import { HttpsProxyAgent } from 'https-proxy-agent' import httpsProxyAgent from 'https-proxy-agent'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import axios from 'axios'
import { sendResponse } from '../utils' import { sendResponse } from '../utils'
import { isNotEmptyString } from '../utils/is' import { isNotEmptyString } from '../utils/is'
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types' import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
import type { RequestOptions } from './types' import type { BalanceResponse, RequestOptions } from './types'
const { HttpsProxyAgent } = httpsProxyAgent
dotenv.config() dotenv.config()
@ -23,6 +24,7 @@ const ErrorCodeMessage: Record<string, string> = {
} }
const timeoutMs: number = !isNaN(+process.env.TIMEOUT_MS) ? +process.env.TIMEOUT_MS : 30 * 1000 const timeoutMs: number = !isNaN(+process.env.TIMEOUT_MS) ? +process.env.TIMEOUT_MS : 30 * 1000
const disableDebug: boolean = process.env.OPENAI_API_DISABLE_DEBUG === 'true'
let apiModel: ApiModel let apiModel: ApiModel
@ -42,7 +44,7 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
const options: ChatGPTAPIOptions = { const options: ChatGPTAPIOptions = {
apiKey: process.env.OPENAI_API_KEY, apiKey: process.env.OPENAI_API_KEY,
completionParams: { model }, completionParams: { model },
debug: true, debug: !disableDebug,
} }
// increase max token limit if use gpt-4 // increase max token limit if use gpt-4
@ -70,13 +72,15 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
const OPENAI_API_MODEL = process.env.OPENAI_API_MODEL const OPENAI_API_MODEL = process.env.OPENAI_API_MODEL
const options: ChatGPTUnofficialProxyAPIOptions = { const options: ChatGPTUnofficialProxyAPIOptions = {
accessToken: process.env.OPENAI_ACCESS_TOKEN, accessToken: process.env.OPENAI_ACCESS_TOKEN,
debug: true, debug: !disableDebug,
} }
if (isNotEmptyString(OPENAI_API_MODEL)) if (isNotEmptyString(OPENAI_API_MODEL))
options.model = OPENAI_API_MODEL options.model = OPENAI_API_MODEL
if (isNotEmptyString(process.env.API_REVERSE_PROXY)) options.apiReverseProxyUrl = isNotEmptyString(process.env.API_REVERSE_PROXY)
options.apiReverseProxyUrl = process.env.API_REVERSE_PROXY ? process.env.API_REVERSE_PROXY
: 'https://bypass.churchless.tech/api/conversation'
setupProxy(options) setupProxy(options)
@ -121,6 +125,8 @@ async function chatReplyProcess(options: RequestOptions) {
} }
async function fetchBalance() { async function fetchBalance() {
// 计算起始日期和结束日期
const OPENAI_API_KEY = process.env.OPENAI_API_KEY const OPENAI_API_KEY = process.env.OPENAI_API_KEY
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL
@ -131,17 +137,38 @@ async function fetchBalance() {
? OPENAI_API_BASE_URL ? OPENAI_API_BASE_URL
: 'https://api.openai.com' : 'https://api.openai.com'
const [startDate, endDate] = formatDate()
// 每月使用量
const urlUsage = `${API_BASE_URL}/v1/dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`
const headers = {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json',
}
try { try {
const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${OPENAI_API_KEY}` } // 获取已使用量
const response = await axios.get(`${API_BASE_URL}/dashboard/billing/credit_grants`, { headers }) const useResponse = await fetch(urlUsage, { headers })
const balance = response.data.total_available ?? 0 const usageData = await useResponse.json() as BalanceResponse
return Promise.resolve(balance.toFixed(3)) const usage = Math.round(usageData.total_usage) / 100
return Promise.resolve(usage ? `$${usage}` : '-')
} }
catch { catch {
return Promise.resolve('-') return Promise.resolve('-')
} }
} }
function formatDate(): string[] {
const today = new Date()
const year = today.getFullYear()
const month = today.getMonth() + 1
const lastDay = new Date(year, month, 0)
const formattedFirstDay = `${year}-${month.toString().padStart(2, '0')}-01`
const formattedLastDay = `${year}-${month.toString().padStart(2, '0')}-${lastDay.getDate().toString().padStart(2, '0')}`
return [formattedFirstDay, formattedLastDay]
}
async function chatConfig() { async function chatConfig() {
const balance = await fetchBalance() const balance = await fetchBalance()
const reverseProxy = process.env.API_REVERSE_PROXY ?? '-' const reverseProxy = process.env.API_REVERSE_PROXY ?? '-'
@ -156,17 +183,19 @@ async function chatConfig() {
} }
function setupProxy(options: ChatGPTAPIOptions | ChatGPTUnofficialProxyAPIOptions) { function setupProxy(options: ChatGPTAPIOptions | ChatGPTUnofficialProxyAPIOptions) {
if (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) { if (isNotEmptyString(process.env.SOCKS_PROXY_HOST) && isNotEmptyString(process.env.SOCKS_PROXY_PORT)) {
const agent = new SocksProxyAgent({ const agent = new SocksProxyAgent({
hostname: process.env.SOCKS_PROXY_HOST, hostname: process.env.SOCKS_PROXY_HOST,
port: process.env.SOCKS_PROXY_PORT, port: process.env.SOCKS_PROXY_PORT,
userId: isNotEmptyString(process.env.SOCKS_PROXY_USERNAME) ? process.env.SOCKS_PROXY_USERNAME : undefined,
password: isNotEmptyString(process.env.SOCKS_PROXY_PASSWORD) ? process.env.SOCKS_PROXY_PASSWORD : undefined,
}) })
options.fetch = (url, options) => { options.fetch = (url, options) => {
return fetch(url, { agent, ...options }) return fetch(url, { agent, ...options })
} }
} }
else { else {
if (process.env.HTTPS_PROXY || process.env.ALL_PROXY) { if (isNotEmptyString(process.env.HTTPS_PROXY) || isNotEmptyString(process.env.ALL_PROXY)) {
const httpsProxy = process.env.HTTPS_PROXY || process.env.ALL_PROXY const httpsProxy = process.env.HTTPS_PROXY || process.env.ALL_PROXY
if (httpsProxy) { if (httpsProxy) {
const agent = new HttpsProxyAgent(httpsProxy) const agent = new HttpsProxyAgent(httpsProxy)

View File

@ -6,3 +6,7 @@ export interface RequestOptions {
process?: (chat: ChatMessage) => void process?: (chat: ChatMessage) => void
systemMessage?: string systemMessage?: string
} }
export interface BalanceResponse {
total_usage: number
}

View File

@ -82,5 +82,6 @@ router.post('/verify', async (req, res) => {
app.use('', router) app.use('', router)
app.use('/api', router) app.use('/api', router)
app.set('trust proxy', 1)
app.listen(3002, () => globalThis.console.log('Server is running on port 3002')) app.listen(3002, () => globalThis.console.log('Server is running on port 3002'))

View File

@ -4,7 +4,7 @@ export default defineConfig({
entry: ['src/index.ts'], entry: ['src/index.ts'],
outDir: 'build', outDir: 'build',
target: 'es2020', target: 'es2020',
format: ['cjs'], format: ['esm'],
splitting: false, splitting: false,
sourcemap: true, sourcemap: true,
minify: false, minify: false,

View File

@ -147,7 +147,7 @@ const clearPromptTemplate = () => {
message.success(t('common.clearSuccess')) message.success(t('common.clearSuccess'))
} }
const importPromptTemplate = () => { const importPromptTemplate = (from = 'online') => {
try { try {
const jsonData = JSON.parse(tempPromptValue.value) const jsonData = JSON.parse(tempPromptValue.value)
let key = '' let key = ''
@ -168,7 +168,7 @@ const importPromptTemplate = () => {
} }
for (const i of jsonData) { for (const i of jsonData) {
if (!('key' in i) || !('value' in i)) if (!(key in i) || !(value in i))
throw new Error(t('store.importError')) throw new Error(t('store.importError'))
let safe = true let safe = true
for (const j of promptList.value) { for (const j of promptList.value) {
@ -191,6 +191,8 @@ const importPromptTemplate = () => {
catch { catch {
message.error('JSON 格式错误,请检查 JSON 格式') message.error('JSON 格式错误,请检查 JSON 格式')
} }
if (from === 'local')
showModal.value = !showModal.value
} }
// //
@ -469,7 +471,7 @@ const dataSource = computed(() => {
block block
type="primary" type="primary"
:disabled="inputStatus" :disabled="inputStatus"
@click="() => { importPromptTemplate() }" @click="() => { importPromptTemplate('local') }"
> >
{{ t('common.import') }} {{ t('common.import') }}
</NButton> </NButton>

View File

@ -63,6 +63,7 @@ onMounted(() => {
<p>{{ $t("setting.api") }}{{ config?.apiModel ?? '-' }}</p> <p>{{ $t("setting.api") }}{{ config?.apiModel ?? '-' }}</p>
<p v-if="isChatGPTAPI"> <p v-if="isChatGPTAPI">
{{ $t("setting.balance") }}{{ config?.balance ?? '-' }} {{ $t("setting.balance") }}{{ config?.balance ?? '-' }}
<span class="text-xs text-neutral-400">({{ $t('setting.monthlyUsage') }})</span>
</p> </p>
<p v-if="!isChatGPTAPI"> <p v-if="!isChatGPTAPI">
{{ $t("setting.reverseProxy") }}{{ config?.reverseProxy ?? '-' }} {{ $t("setting.reverseProxy") }}{{ config?.reverseProxy ?? '-' }}

View File

@ -29,7 +29,7 @@ function handleReset() {
<div class="flex items-center space-x-4"> <div class="flex items-center space-x-4">
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.role') }}</span> <span class="flex-shrink-0 w-[100px]">{{ $t('setting.role') }}</span>
<div class="flex-1"> <div class="flex-1">
<NInput v-model:value="systemMessage" placeholder="" /> <NInput v-model:value="systemMessage" type="textarea" :autosize="{ minRows: 1, maxRows: 4 }" />
</div> </div>
<NButton size="tiny" text type="primary" @click="updateSettings({ systemMessage })"> <NButton size="tiny" text type="primary" @click="updateSettings({ systemMessage })">
{{ $t('common.save') }} {{ $t('common.save') }}

View File

@ -28,7 +28,8 @@ export default {
unauthorizedTips: 'Unauthorized, please verify first.', unauthorizedTips: 'Unauthorized, please verify first.',
}, },
chat: { chat: {
placeholder: 'Ask me anything...(Shift + Enter = line break)', newChatButton: 'New Chat',
placeholder: 'Ask me anything...(Shift + Enter = line break, "/" to trigger prompts)',
placeholderMobile: 'Ask me anything...', placeholderMobile: 'Ask me anything...',
copy: 'Copy', copy: 'Copy',
copied: 'Copied', copied: 'Copied',
@ -68,8 +69,10 @@ export default {
socks: 'Socks', socks: 'Socks',
httpsProxy: 'HTTPS Proxy', httpsProxy: 'HTTPS Proxy',
balance: 'API Balance', balance: 'API Balance',
monthlyUsage: 'Monthly Usage',
}, },
store: { store: {
siderButton: 'Prompt Store',
local: 'Local', local: 'Local',
online: 'Online', online: 'Online',
title: 'Title', title: 'Title',

View File

@ -28,7 +28,8 @@ export default {
unauthorizedTips: '未经授权,请先进行验证。', unauthorizedTips: '未经授权,请先进行验证。',
}, },
chat: { chat: {
placeholder: '来说点什么吧...Shift + Enter = 换行)', newChatButton: '新建聊天',
placeholder: '来说点什么吧...Shift + Enter = 换行,"/" 触发提示词)',
placeholderMobile: '来说点什么...', placeholderMobile: '来说点什么...',
copy: '复制', copy: '复制',
copied: '复制成功', copied: '复制成功',
@ -68,8 +69,10 @@ export default {
socks: 'Socks', socks: 'Socks',
httpsProxy: 'HTTPS Proxy', httpsProxy: 'HTTPS Proxy',
balance: 'API余额', balance: 'API余额',
monthlyUsage: '本月使用量',
}, },
store: { store: {
siderButton: '提示词商店',
local: '本地', local: '本地',
online: '在线', online: '在线',
title: '标题', title: '标题',

View File

@ -28,7 +28,8 @@ export default {
unauthorizedTips: '未經授權,請先進行驗證。', unauthorizedTips: '未經授權,請先進行驗證。',
}, },
chat: { chat: {
placeholder: '來說點什麼...Shift + Enter = 換行)', newChatButton: '新建對話',
placeholder: '來說點什麼...Shift + Enter = 換行,"/" 觸發提示詞)',
placeholderMobile: '來說點什麼...', placeholderMobile: '來說點什麼...',
copy: '複製', copy: '複製',
copied: '複製成功', copied: '複製成功',
@ -68,8 +69,10 @@ export default {
socks: 'Socks', socks: 'Socks',
httpsProxy: 'HTTPS Proxy', httpsProxy: 'HTTPS Proxy',
balance: 'API余額', balance: 'API余額',
monthlyUsage: '本月使用量',
}, },
store: { store: {
siderButton: '提示詞商店',
local: '本機', local: '本機',
online: '線上', online: '線上',
title: '標題', title: '標題',

View File

@ -7,9 +7,8 @@ export interface SettingsState {
} }
export function defaultSetting(): SettingsState { export function defaultSetting(): SettingsState {
const currentDate = new Date().toISOString().split('T')[0]
return { return {
systemMessage: `You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.\nKnowledge cutoff: 2021-09-01\nCurrent date: ${currentDate}`, systemMessage: 'You are ChatGPT, a large language model trained by OpenAI. Follow the user\'s instructions carefully. Respond using markdown.',
} }
} }

View File

@ -123,7 +123,10 @@ html {
} }
code.hljs { code.hljs {
padding: 3px 5px padding: 3px 5px;
&::-webkit-scrollbar {
height: 4px;
}
} }
.hljs { .hljs {

View File

@ -0,0 +1,18 @@
type CallbackFunc<T extends unknown[]> = (...args: T) => void
export function debounce<T extends unknown[]>(
func: CallbackFunc<T>,
wait: number,
): (...args: T) => void {
let timeoutId: ReturnType<typeof setTimeout> | undefined
return (...args: T) => {
const later = () => {
clearTimeout(timeoutId)
func(...args)
}
clearTimeout(timeoutId)
timeoutId = setTimeout(later, wait)
}
}

View File

@ -65,18 +65,14 @@ defineExpose({ textRef })
<template> <template>
<div class="text-black" :class="wrapClass"> <div class="text-black" :class="wrapClass">
<template v-if="loading">
<span class="dark:text-white w-[4px] h-[20px] block animate-blink" />
</template>
<template v-else>
<div ref="textRef" class="leading-relaxed break-words"> <div ref="textRef" class="leading-relaxed break-words">
<div v-if="!inversion"> <div v-if="!inversion" class="flex items-end">
<div v-if="!asRawText" class="markdown-body" v-html="text" /> <div v-if="!asRawText" class="w-full markdown-body" v-html="text" />
<div v-else class="whitespace-pre-wrap" v-text="text" /> <div v-else class="w-full whitespace-pre-wrap" v-text="text" />
<span v-if="loading" class="dark:text-white w-[4px] h-[20px] block animate-blink" />
</div> </div>
<div v-else class="whitespace-pre-wrap" v-text="text" /> <div v-else class="whitespace-pre-wrap" v-text="text" />
</div> </div>
</template>
</div> </div>
</template> </template>

View File

@ -7,6 +7,7 @@ import { SvgIcon } from '@/components/common'
import { copyText } from '@/utils/format' import { copyText } from '@/utils/format'
import { useIconRender } from '@/hooks/useIconRender' import { useIconRender } from '@/hooks/useIconRender'
import { t } from '@/locales' import { t } from '@/locales'
import { useBasicLayout } from '@/hooks/useBasicLayout'
interface Props { interface Props {
dateTime?: string dateTime?: string
@ -25,6 +26,8 @@ const props = defineProps<Props>()
const emit = defineEmits<Emit>() const emit = defineEmits<Emit>()
const { isMobile } = useBasicLayout()
const { iconRender } = useIconRender() const { iconRender } = useIconRender()
const textRef = ref<HTMLElement>() const textRef = ref<HTMLElement>()
@ -113,7 +116,12 @@ function handleRegenerate() {
> >
<SvgIcon icon="ri:restart-line" /> <SvgIcon icon="ri:restart-line" />
</button> </button>
<NDropdown :placement="!inversion ? 'right' : 'left'" :options="options" @select="handleSelect"> <NDropdown
:trigger="isMobile ? 'click' : 'hover'"
:placement="!inversion ? 'right' : 'left'"
:options="options"
@select="handleSelect"
>
<button class="transition text-neutral-300 hover:text-neutral-800 dark:hover:text-neutral-200"> <button class="transition text-neutral-300 hover:text-neutral-800 dark:hover:text-neutral-200">
<SvgIcon icon="ri:more-2-fill" /> <SvgIcon icon="ri:more-2-fill" />
</button> </button>

View File

@ -128,10 +128,10 @@ async function onConversation() {
dataSources.value.length - 1, dataSources.value.length - 1,
{ {
dateTime: new Date().toLocaleString(), dateTime: new Date().toLocaleString(),
text: lastText + data.text ?? '', text: lastText + (data.text ?? ''),
inversion: false, inversion: false,
error: false, error: false,
loading: false, loading: true,
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id }, conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
requestOptions: { prompt: message, options: { ...options } }, requestOptions: { prompt: message, options: { ...options } },
}, },
@ -151,6 +151,7 @@ async function onConversation() {
} }
}, },
}) })
updateChatSome(+uuid, dataSources.value.length - 1, { loading: false })
} }
await fetchChatAPIOnce() await fetchChatAPIOnce()
@ -232,7 +233,7 @@ async function onRegenerate(index: number) {
error: false, error: false,
loading: true, loading: true,
conversationOptions: null, conversationOptions: null,
requestOptions: { prompt: message, ...options }, requestOptions: { prompt: message, options: { ...options } },
}, },
) )
@ -258,12 +259,12 @@ async function onRegenerate(index: number) {
index, index,
{ {
dateTime: new Date().toLocaleString(), dateTime: new Date().toLocaleString(),
text: lastText + data.text ?? '', text: lastText + (data.text ?? ''),
inversion: false, inversion: false,
error: false, error: false,
loading: false, loading: true,
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id }, conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
requestOptions: { prompt: message, ...options }, requestOptions: { prompt: message, options: { ...options } },
}, },
) )
@ -279,6 +280,7 @@ async function onRegenerate(index: number) {
} }
}, },
}) })
updateChatSome(+uuid, index, { loading: false })
} }
await fetchChatAPIOnce() await fetchChatAPIOnce()
} }
@ -306,7 +308,7 @@ async function onRegenerate(index: number) {
error: true, error: true,
loading: false, loading: false,
conversationOptions: null, conversationOptions: null,
requestOptions: { prompt: message, ...options }, requestOptions: { prompt: message, options: { ...options } },
}, },
) )
} }
@ -454,7 +456,7 @@ const footerClass = computed(() => {
onMounted(() => { onMounted(() => {
scrollToBottom() scrollToBottom()
if (inputRef.value) if (inputRef.value && !isMobile.value)
inputRef.value?.focus() inputRef.value?.focus()
}) })
@ -473,11 +475,7 @@ onUnmounted(() => {
@toggle-using-context="toggleUsingContext" @toggle-using-context="toggleUsingContext"
/> />
<main class="flex-1 overflow-hidden"> <main class="flex-1 overflow-hidden">
<div <div id="scrollRef" ref="scrollRef" class="h-full overflow-hidden overflow-y-auto">
id="scrollRef"
ref="scrollRef"
class="h-full overflow-hidden overflow-y-auto"
>
<div <div
id="image-wrapper" id="image-wrapper"
class="w-full max-w-screen-xl m-auto dark:bg-[#101014]" class="w-full max-w-screen-xl m-auto dark:bg-[#101014]"

View File

@ -4,6 +4,7 @@ import { NInput, NPopconfirm, NScrollbar } from 'naive-ui'
import { SvgIcon } from '@/components/common' import { SvgIcon } from '@/components/common'
import { useAppStore, useChatStore } from '@/store' import { useAppStore, useChatStore } from '@/store'
import { useBasicLayout } from '@/hooks/useBasicLayout' import { useBasicLayout } from '@/hooks/useBasicLayout'
import { debounce } from '@/utils/functions/debounce'
const { isMobile } = useBasicLayout() const { isMobile } = useBasicLayout()
@ -32,8 +33,12 @@ function handleEdit({ uuid }: Chat.History, isEdit: boolean, event?: MouseEvent)
function handleDelete(index: number, event?: MouseEvent | TouchEvent) { function handleDelete(index: number, event?: MouseEvent | TouchEvent) {
event?.stopPropagation() event?.stopPropagation()
chatStore.deleteHistory(index) chatStore.deleteHistory(index)
if (isMobile.value)
appStore.setSiderCollapsed(true)
} }
const handleDeleteDebounce = debounce(handleDelete, 600)
function handleEnter({ uuid }: Chat.History, isEdit: boolean, event: KeyboardEvent) { function handleEnter({ uuid }: Chat.History, isEdit: boolean, event: KeyboardEvent) {
event?.stopPropagation() event?.stopPropagation()
if (event.key === 'Enter') if (event.key === 'Enter')
@ -67,8 +72,7 @@ function isActive(uuid: number) {
<div class="relative flex-1 overflow-hidden break-all text-ellipsis whitespace-nowrap"> <div class="relative flex-1 overflow-hidden break-all text-ellipsis whitespace-nowrap">
<NInput <NInput
v-if="item.isEdit" v-if="item.isEdit"
v-model:value="item.title" v-model:value="item.title" size="tiny"
size="tiny"
@keypress="handleEnter(item, false, $event)" @keypress="handleEnter(item, false, $event)"
/> />
<span v-else>{{ item.title }}</span> <span v-else>{{ item.title }}</span>
@ -83,7 +87,7 @@ function isActive(uuid: number) {
<button class="p-1"> <button class="p-1">
<SvgIcon icon="ri:edit-line" @click="handleEdit(item, true, $event)" /> <SvgIcon icon="ri:edit-line" @click="handleEdit(item, true, $event)" />
</button> </button>
<NPopconfirm placement="bottom" @positive-click="handleDelete(index, $event)"> <NPopconfirm placement="bottom" @positive-click="handleDeleteDebounce(index, $event)">
<template #trigger> <template #trigger>
<button class="p-1"> <button class="p-1">
<SvgIcon icon="ri:delete-bin-line" /> <SvgIcon icon="ri:delete-bin-line" />

View File

@ -73,7 +73,7 @@ watch(
<main class="flex flex-col flex-1 min-h-0"> <main class="flex flex-col flex-1 min-h-0">
<div class="p-4"> <div class="p-4">
<NButton dashed block @click="handleAdd"> <NButton dashed block @click="handleAdd">
New chat {{ $t('chat.newChatButton') }}
</NButton> </NButton>
</div> </div>
<div class="flex-1 min-h-0 pb-4 overflow-hidden"> <div class="flex-1 min-h-0 pb-4 overflow-hidden">
@ -81,7 +81,7 @@ watch(
</div> </div>
<div class="p-4"> <div class="p-4">
<NButton block @click="show = true"> <NButton block @click="show = true">
Prompt Store {{ $t('store.siderButton') }}
</NButton> </NButton>
</div> </div>
</main> </main>