Compare commits
1 Commits
main
...
message-ou
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88740c13f0 |
@@ -1,2 +0,0 @@
|
|||||||
docker-compose
|
|
||||||
kubernetes
|
|
||||||
22
.github/workflows/issues_close.yml
vendored
22
.github/workflows/issues_close.yml
vendored
@@ -1,22 +0,0 @@
|
|||||||
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: 2
|
|
||||||
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 2 days since being marked as stale.
|
|
||||||
days-before-pr-stale: -1
|
|
||||||
days-before-pr-close: -1
|
|
||||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
56
CHANGELOG.md
56
CHANGELOG.md
@@ -1,57 +1,3 @@
|
|||||||
## v2.11.0
|
|
||||||
|
|
||||||
`2023-04-26`
|
|
||||||
|
|
||||||
> [chatgpt-web-plus](https://github.com/Chanzhaoyu/chatgpt-web-plus) 新界面、完整用户管理
|
|
||||||
|
|
||||||
## Enhancement
|
|
||||||
- 更新默认 `accessToken` 反代地址为 [[pengzhile](https://github.com/pengzhile)] 的 `https://ai.fakeopen.com/api/conversation` [[24min](https://github.com/Chanzhaoyu/chatgpt-web/pull/1567/files)]
|
|
||||||
- 添加自定义 `temperature` 和 `top_p` [[quzard](https://github.com/Chanzhaoyu/chatgpt-web/pull/1260)]
|
|
||||||
- 优化代码 [[shunyue1320](https://github.com/Chanzhaoyu/chatgpt-web/pull/1328)]
|
|
||||||
- 优化复制代码反馈效果
|
|
||||||
|
|
||||||
## BugFix
|
|
||||||
- 修复余额查询和文案 [[luckywangxi](https://github.com/Chanzhaoyu/chatgpt-web/pull/1174)][[zuoning777](https://github.com/Chanzhaoyu/chatgpt-web/pull/1296)]
|
|
||||||
- 修复默认语言错误 [[idawnwon](https://github.com/Chanzhaoyu/chatgpt-web/pull/1352)]
|
|
||||||
- 修复 `onRegenerate` 下问题 [[leafsummer](https://github.com/Chanzhaoyu/chatgpt-web/pull/1188)]
|
|
||||||
|
|
||||||
## Other
|
|
||||||
- 引导用户触发提示词 [[RyanXinOne](https://github.com/Chanzhaoyu/chatgpt-web/pull/1183)]
|
|
||||||
- 添加韩语翻译 [[Kamilake](https://github.com/Chanzhaoyu/chatgpt-web/pull/1372)]
|
|
||||||
- 添加俄语翻译 [[aquaratixc](https://github.com/Chanzhaoyu/chatgpt-web/pull/1571)]
|
|
||||||
- 优化翻译和文本检查 [[PeterDaveHello](https://github.com/Chanzhaoyu/chatgpt-web/pull/1460)]
|
|
||||||
- 移除无用文件
|
|
||||||
|
|
||||||
## v2.10.9
|
|
||||||
|
|
||||||
`2023-04-03`
|
|
||||||
|
|
||||||
> 更新默认 `accessToken` 反代地址为 [[pengzhile](https://github.com/pengzhile)] 的 `https://ai.fakeopen.com/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`
|
||||||
@@ -125,7 +71,7 @@
|
|||||||
|
|
||||||
`2023-03-13`
|
`2023-03-13`
|
||||||
|
|
||||||
更新依赖,`access_token` 默认代理为 [pengzhile](https://github.com/pengzhile) 的 `https://bypass.duti.tech/api/conversation`
|
更新依赖,`access_token` 默认代理为 [acheong08](https://github.com/acheong08) 的 `https://bypass.duti.tech/api/conversation`
|
||||||
|
|
||||||
## Feature
|
## Feature
|
||||||
- `Prompt` 商店在线导入可以导入两种 `recommend.json`里提到的模板 [simonwu53](https://github.com/Chanzhaoyu/chatgpt-web/pull/521)
|
- `Prompt` 商店在线导入可以导入两种 `recommend.json`里提到的模板 [simonwu53](https://github.com/Chanzhaoyu/chatgpt-web/pull/521)
|
||||||
|
|||||||
337
README.en.md
Normal file
337
README.en.md
Normal file
@@ -0,0 +1,337 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
- [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 Password,optional
|
||||||
|
- `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 http,https, socks5
|
||||||
|
- `ALL_PROXY` optional, support http,https, socks5
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
#### 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 password,optional
|
||||||
|
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 Proxy,optional, 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
|
||||||
|
|
||||||
|
[](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.
|
||||||
|
|
||||||
|
Q: The content returned is incomplete?
|
||||||
|
|
||||||
|
A: There is a length limit for the content returned by the API each time. You can modify the `VITE_GLOB_OPEN_LONG_REPLY` field in the `.env` file under the root directory, set it to `true`, and rebuild the front-end to enable the long reply feature, which can return the full content. It should be noted that using this feature may bring more API usage fees.
|
||||||
|
|
||||||
|
## 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)
|
||||||
35
README.md
35
README.md
@@ -1,8 +1,12 @@
|
|||||||
# ChatGPT Web
|
# ChatGPT Web
|
||||||
|
|
||||||
> 声明:此项目只发布于 GitHub,基于 MIT 协议,免费且作为开源学习使用。并且不会有任何形式的卖号、付费服务、讨论群、讨论组等行为。谨防受骗。
|
<div style="font-size: 1.5rem;">
|
||||||
|
<a href="./README.md">中文</a> |
|
||||||
|
<a href="./README.en.md">English</a>
|
||||||
|
</div>
|
||||||
|
</br>
|
||||||
|
|
||||||
更多功能:[chatgpt-web-plus](https://github.com/Chanzhaoyu/chatgpt-web-plus)
|
> 声明:此项目只发布于 Github,基于 MIT 协议,免费且作为开源学习使用。并且不会有任何形式的卖号、付费服务、讨论群、讨论组等行为。谨防受骗。
|
||||||
|
|
||||||

|

|
||||||

|

|
||||||
@@ -26,7 +30,6 @@
|
|||||||
- [Docker 参数示例](#docker-参数示例)
|
- [Docker 参数示例](#docker-参数示例)
|
||||||
- [Docker build \& Run](#docker-build--run)
|
- [Docker build \& Run](#docker-build--run)
|
||||||
- [Docker compose](#docker-compose)
|
- [Docker compose](#docker-compose)
|
||||||
- [防止爬虫抓取](#防止爬虫抓取)
|
|
||||||
- [使用 Railway 部署](#使用-railway-部署)
|
- [使用 Railway 部署](#使用-railway-部署)
|
||||||
- [Railway 环境变量](#railway-环境变量)
|
- [Railway 环境变量](#railway-环境变量)
|
||||||
- [手动打包](#手动打包)
|
- [手动打包](#手动打包)
|
||||||
@@ -46,14 +49,14 @@
|
|||||||
| `ChatGPTUnofficialProxyAPI(网页 accessToken)` | 是 | 相对不可靠 | 聪明 |
|
| `ChatGPTUnofficialProxyAPI(网页 accessToken)` | 是 | 相对不可靠 | 聪明 |
|
||||||
|
|
||||||
对比:
|
对比:
|
||||||
1. `ChatGPTAPI` 使用 `gpt-3.5-turbo` 通过 `OpenAI` 官方 `API` 调用 `ChatGPT`
|
1. `ChatGPTAPI` 使用 `gpt-3.5-turbo-0301` 通过官方`OpenAI`补全`API`模拟`ChatGPT`(最稳健的方法,但它不是免费的,并且没有使用针对聊天进行微调的模型)
|
||||||
2. `ChatGPTUnofficialProxyAPI` 使用非官方代理服务器访问 `ChatGPT` 的后端`API`,绕过`Cloudflare`(依赖于第三方服务器,并且有速率限制)
|
2. `ChatGPTUnofficialProxyAPI` 使用非官方代理服务器访问 `ChatGPT` 的后端`API`,绕过`Cloudflare`(使用真实的的`ChatGPT`,非常轻量级,但依赖于第三方服务器,并且有速率限制)
|
||||||
|
|
||||||
警告:
|
警告:
|
||||||
1. 你应该首先使用 `API` 方式
|
1. 你应该首先使用 `API` 方式
|
||||||
2. 使用 `API` 时,如果网络不通,那是国内被墙了,你需要自建代理,绝对不要使用别人的公开代理,那是危险的。
|
2. 使用 `API` 时,如果网络不通,那是国内被墙了,你需要自建代理,绝对不要使用别人的公开代理,那是危险的。
|
||||||
3. 使用 `accessToken` 方式时反向代理将向第三方暴露您的访问令牌,这样做应该不会产生任何不良影响,但在使用这种方法之前请考虑风险。
|
3. 使用 `accessToken` 方式时反向代理将向第三方暴露您的访问令牌,这样做应该不会产生任何不良影响,但在使用这种方法之前请考虑风险。
|
||||||
4. 使用 `accessToken` 时,不管你是国内还是国外的机器,都会使用代理。默认代理为 [pengzhile](https://github.com/pengzhile) 大佬的 `https://ai.fakeopen.com/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`,防止被关键词搜索到。
|
||||||
|
|
||||||
切换方式:
|
切换方式:
|
||||||
@@ -158,12 +161,11 @@ 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://ai.fakeopen.com/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)(注意:只有这两个是推荐,其他第三方来源,请自行甄别)
|
||||||
|
|
||||||
通用:
|
通用:
|
||||||
|
|
||||||
@@ -237,21 +239,6 @@ services:
|
|||||||
```
|
```
|
||||||
- `OPENAI_API_BASE_URL` 可选,设置 `OPENAI_API_KEY` 时可用
|
- `OPENAI_API_BASE_URL` 可选,设置 `OPENAI_API_KEY` 时可用
|
||||||
- `OPENAI_API_MODEL` 可选,设置 `OPENAI_API_KEY` 时可用
|
- `OPENAI_API_MODEL` 可选,设置 `OPENAI_API_KEY` 时可用
|
||||||
|
|
||||||
#### 防止爬虫抓取
|
|
||||||
|
|
||||||
**nginx**
|
|
||||||
|
|
||||||
将下面配置填入nginx配置文件中,可以参考 `docker-compose/nginx/nginx.conf` 文件中添加反爬虫的方法
|
|
||||||
|
|
||||||
```
|
|
||||||
# 防止爬虫抓取
|
|
||||||
if ($http_user_agent ~* "360Spider|JikeSpider|Spider|spider|bot|Bot|2345Explorer|curl|wget|webZIP|qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Feedfetcher-Google|Yahoo! Slurp|Yahoo! Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot|ia_archiver|Tomato Bot|NSPlayer|bingbot")
|
|
||||||
{
|
|
||||||
return 403;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 使用 Railway 部署
|
### 使用 Railway 部署
|
||||||
|
|
||||||
[](https://railway.app/new/template/yytmgc)
|
[](https://railway.app/new/template/yytmgc)
|
||||||
@@ -271,8 +258,6 @@ 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 代理,支持 http,https, socks5 |
|
| `HTTPS_PROXY` | 可选 | HTTPS 代理,支持 http,https, socks5 |
|
||||||
| `ALL_PROXY` | 可选 | 所有代理 代理,支持 http,https, socks5 |
|
| `ALL_PROXY` | 可选 | 所有代理 代理,支持 http,https, socks5 |
|
||||||
|
|
||||||
|
|||||||
1
config/index.ts
Normal file
1
config/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './proxy'
|
||||||
16
config/proxy.ts
Normal file
16
config/proxy.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import type { ProxyOptions } from 'vite'
|
||||||
|
|
||||||
|
export function createViteProxy(isOpenProxy: boolean, viteEnv: ImportMetaEnv) {
|
||||||
|
if (!isOpenProxy)
|
||||||
|
return
|
||||||
|
|
||||||
|
const proxy: Record<string, string | ProxyOptions> = {
|
||||||
|
'/api': {
|
||||||
|
target: viteEnv.VITE_APP_API_BASE_URL,
|
||||||
|
changeOrigin: true,
|
||||||
|
rewrite: path => path.replace('/api/', '/'),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
@@ -2,39 +2,33 @@ 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:
|
OPENAI_API_KEY: sk-xxx
|
||||||
# 二选一
|
# 二选一
|
||||||
OPENAI_ACCESS_TOKEN:
|
OPENAI_ACCESS_TOKEN: xxx
|
||||||
# API接口地址,可选,设置 OPENAI_API_KEY 时可用
|
# API接口地址,可选,设置 OPENAI_API_KEY 时可用
|
||||||
OPENAI_API_BASE_URL:
|
OPENAI_API_BASE_URL: xxx
|
||||||
# API模型,可选,设置 OPENAI_API_KEY 时可用
|
# API模型,可选,设置 OPENAI_API_KEY 时可用
|
||||||
OPENAI_API_MODEL:
|
OPENAI_API_MODEL: xxx
|
||||||
# 反向代理,可选
|
# 反向代理,可选
|
||||||
API_REVERSE_PROXY:
|
API_REVERSE_PROXY: xxx
|
||||||
# 访问权限密钥,可选
|
# 访问权限密钥,可选
|
||||||
AUTH_SECRET_KEY:
|
AUTH_SECRET_KEY: xxx
|
||||||
# 每小时最大请求次数,可选,默认无限
|
# 每小时最大请求次数,可选,默认无限
|
||||||
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:
|
SOCKS_PROXY_HOST: xxx
|
||||||
# Socks代理端口,可选,和 SOCKS_PROXY_HOST 一起时生效
|
# Socks代理端口,可选,和 SOCKS_PROXY_HOST 一起时生效
|
||||||
SOCKS_PROXY_PORT:
|
SOCKS_PROXY_PORT: xxx
|
||||||
# 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:
|
HTTPS_PROXY: http://xxx:7890
|
||||||
nginx:
|
nginx:
|
||||||
container_name: nginx
|
|
||||||
image: nginx:alpine
|
image: nginx:alpine
|
||||||
ports:
|
ports:
|
||||||
- '80:80'
|
- '80:80'
|
||||||
|
|||||||
@@ -3,13 +3,6 @@ server {
|
|||||||
server_name localhost;
|
server_name localhost;
|
||||||
charset utf-8;
|
charset utf-8;
|
||||||
error_page 500 502 503 504 /50x.html;
|
error_page 500 502 503 504 /50x.html;
|
||||||
|
|
||||||
# 防止爬虫抓取
|
|
||||||
if ($http_user_agent ~* "360Spider|JikeSpider|Spider|spider|bot|Bot|2345Explorer|curl|wget|webZIP|qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Feedfetcher-Google|Yahoo! Slurp|Yahoo! Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot|ia_archiver|Tomato Bot|NSPlayer|bingbot")
|
|
||||||
{
|
|
||||||
return 403;
|
|
||||||
}
|
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
root /usr/share/nginx/html;
|
root /usr/share/nginx/html;
|
||||||
try_files $uri /index.html;
|
try_files $uri /index.html;
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
## 增加一个Kubernetes的部署方式
|
|
||||||
```
|
|
||||||
kubectl apply -f deploy.yaml
|
|
||||||
```
|
|
||||||
|
|
||||||
### 如果需要Ingress域名接入
|
|
||||||
```
|
|
||||||
kubectl apply -f ingress.yaml
|
|
||||||
```
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
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://ai.fakeopen.com/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
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
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
|
|
||||||
19631
package-lock.json
generated
19631
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "chatgpt-web",
|
"name": "chatgpt-web",
|
||||||
"version": "2.11.0",
|
"version": "2.10.8",
|
||||||
"private": false,
|
"private": false,
|
||||||
"description": "ChatGPT Web",
|
"description": "ChatGPT Web",
|
||||||
"author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>",
|
"author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>",
|
||||||
|
|||||||
2331
pnpm-lock.yaml
generated
2331
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -10,12 +10,7 @@ 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=
|
||||||
|
|
||||||
# set `true` to disable OpenAI API debug log
|
# Reverse Proxy
|
||||||
OPENAI_API_DISABLE_DEBUG=
|
|
||||||
|
|
||||||
# Reverse Proxy - Available on accessToken
|
|
||||||
# Default: https://ai.fakeopen.com/api/conversation
|
|
||||||
# More: https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy
|
|
||||||
API_REVERSE_PROXY=
|
API_REVERSE_PROXY=
|
||||||
|
|
||||||
# timeout
|
# timeout
|
||||||
@@ -33,12 +28,6 @@ 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=
|
||||||
|
|
||||||
|
|||||||
@@ -5,10 +5,11 @@ 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, SetProxyOptions, UsageResponse } from './types'
|
import type { RequestOptions } from './types'
|
||||||
|
|
||||||
const { HttpsProxyAgent } = httpsProxyAgent
|
const { HttpsProxyAgent } = httpsProxyAgent
|
||||||
|
|
||||||
@@ -23,11 +24,9 @@ const ErrorCodeMessage: Record<string, string> = {
|
|||||||
500: '[OpenAI] 服务器繁忙,请稍后再试 | Internal Server Error',
|
500: '[OpenAI] 服务器繁忙,请稍后再试 | Internal Server Error',
|
||||||
}
|
}
|
||||||
|
|
||||||
const timeoutMs: number = !isNaN(+process.env.TIMEOUT_MS) ? +process.env.TIMEOUT_MS : 100 * 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
|
||||||
const model = isNotEmptyString(process.env.OPENAI_API_MODEL) ? process.env.OPENAI_API_MODEL : 'gpt-3.5-turbo'
|
|
||||||
|
|
||||||
if (!isNotEmptyString(process.env.OPENAI_API_KEY) && !isNotEmptyString(process.env.OPENAI_ACCESS_TOKEN))
|
if (!isNotEmptyString(process.env.OPENAI_API_KEY) && !isNotEmptyString(process.env.OPENAI_ACCESS_TOKEN))
|
||||||
throw new Error('Missing OPENAI_API_KEY or OPENAI_ACCESS_TOKEN environment variable')
|
throw new Error('Missing OPENAI_API_KEY or OPENAI_ACCESS_TOKEN environment variable')
|
||||||
@@ -39,11 +38,13 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
|
|||||||
|
|
||||||
if (isNotEmptyString(process.env.OPENAI_API_KEY)) {
|
if (isNotEmptyString(process.env.OPENAI_API_KEY)) {
|
||||||
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL
|
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL
|
||||||
|
const OPENAI_API_MODEL = process.env.OPENAI_API_MODEL
|
||||||
|
const model = isNotEmptyString(OPENAI_API_MODEL) ? OPENAI_API_MODEL : 'gpt-3.5-turbo'
|
||||||
|
|
||||||
const options: ChatGPTAPIOptions = {
|
const options: ChatGPTAPIOptions = {
|
||||||
apiKey: process.env.OPENAI_API_KEY,
|
apiKey: process.env.OPENAI_API_KEY,
|
||||||
completionParams: { model },
|
completionParams: { model },
|
||||||
debug: !disableDebug,
|
debug: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
// increase max token limit if use gpt-4
|
// increase max token limit if use gpt-4
|
||||||
@@ -68,12 +69,16 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
|
|||||||
apiModel = 'ChatGPTAPI'
|
apiModel = 'ChatGPTAPI'
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
|
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,
|
||||||
apiReverseProxyUrl: isNotEmptyString(process.env.API_REVERSE_PROXY) ? process.env.API_REVERSE_PROXY : 'https://ai.fakeopen.com/api/conversation',
|
debug: true,
|
||||||
model,
|
|
||||||
debug: !disableDebug,
|
|
||||||
}
|
}
|
||||||
|
if (isNotEmptyString(OPENAI_API_MODEL))
|
||||||
|
options.model = OPENAI_API_MODEL
|
||||||
|
|
||||||
|
if (isNotEmptyString(process.env.API_REVERSE_PROXY))
|
||||||
|
options.apiReverseProxyUrl = process.env.API_REVERSE_PROXY
|
||||||
|
|
||||||
setupProxy(options)
|
setupProxy(options)
|
||||||
|
|
||||||
@@ -83,14 +88,13 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
|
|||||||
})()
|
})()
|
||||||
|
|
||||||
async function chatReplyProcess(options: RequestOptions) {
|
async function chatReplyProcess(options: RequestOptions) {
|
||||||
const { message, lastContext, process, systemMessage, temperature, top_p } = options
|
const { message, lastContext, process, systemMessage } = options
|
||||||
try {
|
try {
|
||||||
let options: SendMessageOptions = { timeoutMs }
|
let options: SendMessageOptions = { timeoutMs }
|
||||||
|
|
||||||
if (apiModel === 'ChatGPTAPI') {
|
if (apiModel === 'ChatGPTAPI') {
|
||||||
if (isNotEmptyString(systemMessage))
|
if (isNotEmptyString(systemMessage))
|
||||||
options.systemMessage = systemMessage
|
options.systemMessage = systemMessage
|
||||||
options.completionParams = { model, temperature, top_p }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (lastContext != null) {
|
if (lastContext != null) {
|
||||||
@@ -118,7 +122,7 @@ async function chatReplyProcess(options: RequestOptions) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchUsage() {
|
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
|
||||||
|
|
||||||
@@ -129,47 +133,19 @@ async function fetchUsage() {
|
|||||||
? 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',
|
|
||||||
}
|
|
||||||
|
|
||||||
const options = {} as SetProxyOptions
|
|
||||||
|
|
||||||
setupProxy(options)
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 获取已使用量
|
const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${OPENAI_API_KEY}` }
|
||||||
const useResponse = await options.fetch(urlUsage, { headers })
|
const response = await axios.get(`${API_BASE_URL}/dashboard/billing/credit_grants`, { headers })
|
||||||
if (!useResponse.ok)
|
const balance = response.data.total_available ?? 0
|
||||||
throw new Error('获取使用量失败')
|
return Promise.resolve(balance.toFixed(3))
|
||||||
const usageData = await useResponse.json() as UsageResponse
|
|
||||||
const usage = Math.round(usageData.total_usage) / 100
|
|
||||||
return Promise.resolve(usage ? `$${usage}` : '-')
|
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch {
|
||||||
global.console.log(error)
|
|
||||||
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 usage = await fetchUsage()
|
const balance = await fetchBalance()
|
||||||
const reverseProxy = process.env.API_REVERSE_PROXY ?? '-'
|
const reverseProxy = process.env.API_REVERSE_PROXY ?? '-'
|
||||||
const httpsProxy = (process.env.HTTPS_PROXY || process.env.ALL_PROXY) ?? '-'
|
const httpsProxy = (process.env.HTTPS_PROXY || process.env.ALL_PROXY) ?? '-'
|
||||||
const socksProxy = (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT)
|
const socksProxy = (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT)
|
||||||
@@ -177,34 +153,29 @@ async function chatConfig() {
|
|||||||
: '-'
|
: '-'
|
||||||
return sendResponse<ModelConfig>({
|
return sendResponse<ModelConfig>({
|
||||||
type: 'Success',
|
type: 'Success',
|
||||||
data: { apiModel, reverseProxy, timeoutMs, socksProxy, httpsProxy, usage },
|
data: { apiModel, reverseProxy, timeoutMs, socksProxy, httpsProxy, balance },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function setupProxy(options: SetProxyOptions) {
|
function setupProxy(options: ChatGPTAPIOptions | ChatGPTUnofficialProxyAPIOptions) {
|
||||||
if (isNotEmptyString(process.env.SOCKS_PROXY_HOST) && isNotEmptyString(process.env.SOCKS_PROXY_PORT)) {
|
if (process.env.SOCKS_PROXY_HOST && 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 if (isNotEmptyString(process.env.HTTPS_PROXY) || isNotEmptyString(process.env.ALL_PROXY)) {
|
|
||||||
const httpsProxy = process.env.HTTPS_PROXY || process.env.ALL_PROXY
|
|
||||||
if (httpsProxy) {
|
|
||||||
const agent = new HttpsProxyAgent(httpsProxy)
|
|
||||||
options.fetch = (url, options) => {
|
|
||||||
return fetch(url, { agent, ...options })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
else {
|
||||||
options.fetch = (url, options) => {
|
if (process.env.HTTPS_PROXY || process.env.ALL_PROXY) {
|
||||||
return fetch(url, { ...options })
|
const httpsProxy = process.env.HTTPS_PROXY || process.env.ALL_PROXY
|
||||||
|
if (httpsProxy) {
|
||||||
|
const agent = new HttpsProxyAgent(httpsProxy)
|
||||||
|
options.fetch = (url, options) => {
|
||||||
|
return fetch(url, { agent, ...options })
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,8 @@
|
|||||||
import type { ChatMessage } from 'chatgpt'
|
import type { ChatMessage } from 'chatgpt'
|
||||||
import type fetch from 'node-fetch'
|
|
||||||
|
|
||||||
export interface RequestOptions {
|
export interface RequestOptions {
|
||||||
message: string
|
message: string
|
||||||
lastContext?: { conversationId?: string; parentMessageId?: string }
|
lastContext?: { conversationId?: string; parentMessageId?: string }
|
||||||
process?: (chat: ChatMessage) => void
|
process?: (chat: ChatMessage) => void
|
||||||
systemMessage?: string
|
systemMessage?: string
|
||||||
temperature?: number
|
|
||||||
top_p?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SetProxyOptions {
|
|
||||||
fetch?: typeof fetch
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface UsageResponse {
|
|
||||||
total_usage: number
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,18 +23,25 @@ router.post('/chat-process', [auth, limiter], async (req, res) => {
|
|||||||
res.setHeader('Content-type', 'application/octet-stream')
|
res.setHeader('Content-type', 'application/octet-stream')
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { prompt, options = {}, systemMessage, temperature, top_p } = req.body as RequestProps
|
const { prompt, options = {}, systemMessage } = req.body as RequestProps
|
||||||
let firstChunk = true
|
let firstChunk = true
|
||||||
|
let chatLength = 0
|
||||||
|
let newChatLength = 0
|
||||||
await chatReplyProcess({
|
await chatReplyProcess({
|
||||||
message: prompt,
|
message: prompt,
|
||||||
lastContext: options,
|
lastContext: options,
|
||||||
process: (chat: ChatMessage) => {
|
process: (chat: ChatMessage) => {
|
||||||
res.write(firstChunk ? JSON.stringify(chat) : `\n${JSON.stringify(chat)}`)
|
if (firstChunk) {
|
||||||
firstChunk = false
|
res.write(`${JSON.stringify(chat)}t1h1i4s5i1s4a1s9i1l9l8y1s0plit`)
|
||||||
|
firstChunk = false
|
||||||
|
}
|
||||||
|
else if (chatLength !== chat.text.length) {
|
||||||
|
newChatLength = chat.text.length
|
||||||
|
res.write(chat.text.substring(chatLength, newChatLength))
|
||||||
|
chatLength = newChatLength
|
||||||
|
}
|
||||||
},
|
},
|
||||||
systemMessage,
|
systemMessage,
|
||||||
temperature,
|
|
||||||
top_p,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
@@ -78,7 +85,7 @@ router.post('/verify', async (req, res) => {
|
|||||||
res.send({ status: 'Success', message: 'Verify successfully', data: null })
|
res.send({ status: 'Success', message: 'Verify successfully', data: null })
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
res.send({ status: 'Fail', message: error.message, data: null })
|
res.send({ status: 'Fail', message: error.messagen, data: null })
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,6 @@ export interface RequestProps {
|
|||||||
prompt: string
|
prompt: string
|
||||||
options?: ChatContext
|
options?: ChatContext
|
||||||
systemMessage: string
|
systemMessage: string
|
||||||
temperature?: number
|
|
||||||
top_p?: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ChatContext {
|
export interface ChatContext {
|
||||||
@@ -28,7 +26,7 @@ export interface ModelConfig {
|
|||||||
timeoutMs?: number
|
timeoutMs?: number
|
||||||
socksProxy?: string
|
socksProxy?: string
|
||||||
httpsProxy?: string
|
httpsProxy?: string
|
||||||
usage?: string
|
balance?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ApiModel = 'ChatGPTAPI' | 'ChatGPTUnofficialProxyAPI' | undefined
|
export type ApiModel = 'ChatGPTAPI' | 'ChatGPTUnofficialProxyAPI' | undefined
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { AxiosProgressEvent, GenericAbortSignal } from 'axios'
|
import type { AxiosProgressEvent, GenericAbortSignal } from 'axios'
|
||||||
import { post } from '@/utils/request'
|
import { post } from '@/utils/request'
|
||||||
import { useAuthStore, useSettingStore } from '@/store'
|
import { useSettingStore } from '@/store'
|
||||||
|
|
||||||
export function fetchChatAPI<T = any>(
|
export function fetchChatAPI<T = any>(
|
||||||
prompt: string,
|
prompt: string,
|
||||||
@@ -28,25 +28,10 @@ export function fetchChatAPIProcess<T = any>(
|
|||||||
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void },
|
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void },
|
||||||
) {
|
) {
|
||||||
const settingStore = useSettingStore()
|
const settingStore = useSettingStore()
|
||||||
const authStore = useAuthStore()
|
|
||||||
|
|
||||||
let data: Record<string, any> = {
|
|
||||||
prompt: params.prompt,
|
|
||||||
options: params.options,
|
|
||||||
}
|
|
||||||
|
|
||||||
if (authStore.isChatGPTAPI) {
|
|
||||||
data = {
|
|
||||||
...data,
|
|
||||||
systemMessage: settingStore.systemMessage,
|
|
||||||
temperature: settingStore.temperature,
|
|
||||||
top_p: settingStore.top_p,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return post<T>({
|
return post<T>({
|
||||||
url: '/chat-process',
|
url: '/chat-process',
|
||||||
data,
|
data: { prompt: params.prompt, options: params.options, systemMessage: settingStore.systemMessage },
|
||||||
signal: params.signal,
|
signal: params.signal,
|
||||||
onDownloadProgress: params.onDownloadProgress,
|
onDownloadProgress: params.onDownloadProgress,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ interface ConfigState {
|
|||||||
apiModel?: string
|
apiModel?: string
|
||||||
socksProxy?: string
|
socksProxy?: string
|
||||||
httpsProxy?: string
|
httpsProxy?: string
|
||||||
usage?: string
|
balance?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const authStore = useAuthStore()
|
const authStore = useAuthStore()
|
||||||
@@ -52,17 +52,17 @@ onMounted(() => {
|
|||||||
href="https://github.com/Chanzhaoyu/chatgpt-web"
|
href="https://github.com/Chanzhaoyu/chatgpt-web"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
>
|
>
|
||||||
GitHub
|
Github
|
||||||
</a>
|
</a>
|
||||||
,免费且基于 MIT 协议,没有任何形式的付费行为!
|
,免费且基于 MIT 协议,没有任何形式的付费行为!
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
如果你觉得此项目对你有帮助,请在 GitHub 帮我点个 Star 或者给予一点赞助,谢谢!
|
如果你觉得此项目对你有帮助,请在 Github 帮我点个 Star 或者给予一点赞助,谢谢!
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<p>{{ $t("setting.api") }}:{{ config?.apiModel ?? '-' }}</p>
|
<p>{{ $t("setting.api") }}:{{ config?.apiModel ?? '-' }}</p>
|
||||||
<p v-if="isChatGPTAPI">
|
<p v-if="isChatGPTAPI">
|
||||||
{{ $t("setting.monthlyUsage") }}:{{ config?.usage ?? '-' }}
|
{{ $t("setting.balance") }}:{{ config?.balance ?? '-' }}
|
||||||
</p>
|
</p>
|
||||||
<p v-if="!isChatGPTAPI">
|
<p v-if="!isChatGPTAPI">
|
||||||
{{ $t("setting.reverseProxy") }}:{{ config?.reverseProxy ?? '-' }}
|
{{ $t("setting.reverseProxy") }}:{{ config?.reverseProxy ?? '-' }}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { ref } from 'vue'
|
import { ref } from 'vue'
|
||||||
import { NButton, NInput, NSlider, useMessage } from 'naive-ui'
|
import { NButton, NInput, useMessage } from 'naive-ui'
|
||||||
import { useSettingStore } from '@/store'
|
import { useSettingStore } from '@/store'
|
||||||
import type { SettingsState } from '@/store/modules/settings/helper'
|
import type { SettingsState } from '@/store/modules/settings/helper'
|
||||||
import { t } from '@/locales'
|
import { t } from '@/locales'
|
||||||
@@ -11,10 +11,6 @@ const ms = useMessage()
|
|||||||
|
|
||||||
const systemMessage = ref(settingStore.systemMessage ?? '')
|
const systemMessage = ref(settingStore.systemMessage ?? '')
|
||||||
|
|
||||||
const temperature = ref(settingStore.temperature ?? 0.5)
|
|
||||||
|
|
||||||
const top_p = ref(settingStore.top_p ?? 1)
|
|
||||||
|
|
||||||
function updateSettings(options: Partial<SettingsState>) {
|
function updateSettings(options: Partial<SettingsState>) {
|
||||||
settingStore.updateSetting(options)
|
settingStore.updateSetting(options)
|
||||||
ms.success(t('common.success'))
|
ms.success(t('common.success'))
|
||||||
@@ -31,36 +27,16 @@ function handleReset() {
|
|||||||
<div class="p-4 space-y-5 min-h-[200px]">
|
<div class="p-4 space-y-5 min-h-[200px]">
|
||||||
<div class="space-y-6">
|
<div class="space-y-6">
|
||||||
<div class="flex items-center space-x-4">
|
<div class="flex items-center space-x-4">
|
||||||
<span class="flex-shrink-0 w-[120px]">{{ $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" type="textarea" :autosize="{ minRows: 1, maxRows: 4 }" />
|
<NInput v-model:value="systemMessage" placeholder="" />
|
||||||
</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') }}
|
||||||
</NButton>
|
</NButton>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center space-x-4">
|
<div class="flex items-center space-x-4">
|
||||||
<span class="flex-shrink-0 w-[120px]">{{ $t('setting.temperature') }} </span>
|
<span class="flex-shrink-0 w-[100px]"> </span>
|
||||||
<div class="flex-1">
|
|
||||||
<NSlider v-model:value="temperature" :max="1" :min="0" :step="0.1" />
|
|
||||||
</div>
|
|
||||||
<span>{{ temperature }}</span>
|
|
||||||
<NButton size="tiny" text type="primary" @click="updateSettings({ temperature })">
|
|
||||||
{{ $t('common.save') }}
|
|
||||||
</NButton>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center space-x-4">
|
|
||||||
<span class="flex-shrink-0 w-[120px]">{{ $t('setting.top_p') }} </span>
|
|
||||||
<div class="flex-1">
|
|
||||||
<NSlider v-model:value="top_p" :max="1" :min="0" :step="0.1" />
|
|
||||||
</div>
|
|
||||||
<span>{{ top_p }}</span>
|
|
||||||
<NButton size="tiny" text type="primary" @click="updateSettings({ top_p })">
|
|
||||||
{{ $t('common.save') }}
|
|
||||||
</NButton>
|
|
||||||
</div>
|
|
||||||
<div class="flex items-center space-x-4">
|
|
||||||
<span class="flex-shrink-0 w-[120px]"> </span>
|
|
||||||
<NButton size="small" @click="handleReset">
|
<NButton size="small" @click="handleReset">
|
||||||
{{ $t('common.reset') }}
|
{{ $t('common.reset') }}
|
||||||
</NButton>
|
</NButton>
|
||||||
|
|||||||
@@ -57,8 +57,6 @@ const languageOptions: { label: string; key: Language; value: Language }[] = [
|
|||||||
{ label: '简体中文', key: 'zh-CN', value: 'zh-CN' },
|
{ label: '简体中文', key: 'zh-CN', value: 'zh-CN' },
|
||||||
{ label: '繁體中文', key: 'zh-TW', value: 'zh-TW' },
|
{ label: '繁體中文', key: 'zh-TW', value: 'zh-TW' },
|
||||||
{ label: 'English', key: 'en-US', value: 'en-US' },
|
{ label: 'English', key: 'en-US', value: 'en-US' },
|
||||||
{ label: '한국어', key: 'ko-KR', value: 'ko-KR' },
|
|
||||||
{ label: 'Русский язык', key: 'ru-RU', value: 'ru-RU' },
|
|
||||||
]
|
]
|
||||||
|
|
||||||
function updateUserInfo(options: Partial<UserInfo>) {
|
function updateUserInfo(options: Partial<UserInfo>) {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { computed } from 'vue'
|
import { computed } from 'vue'
|
||||||
import { enUS, koKR, zhCN, zhTW } from 'naive-ui'
|
import { enUS, zhCN, zhTW } from 'naive-ui'
|
||||||
import { useAppStore } from '@/store'
|
import { useAppStore } from '@/store'
|
||||||
import { setLocale } from '@/locales'
|
import { setLocale } from '@/locales'
|
||||||
|
|
||||||
@@ -11,12 +11,6 @@ export function useLanguage() {
|
|||||||
case 'en-US':
|
case 'en-US':
|
||||||
setLocale('en-US')
|
setLocale('en-US')
|
||||||
return enUS
|
return enUS
|
||||||
case 'ru-RU':
|
|
||||||
setLocale('ru-RU')
|
|
||||||
return enUS
|
|
||||||
case 'ko-KR':
|
|
||||||
setLocale('ko-KR')
|
|
||||||
return koKR
|
|
||||||
case 'zh-CN':
|
case 'zh-CN':
|
||||||
setLocale('zh-CN')
|
setLocale('zh-CN')
|
||||||
return zhCN
|
return zhCN
|
||||||
@@ -25,7 +19,7 @@ export function useLanguage() {
|
|||||||
return zhTW
|
return zhTW
|
||||||
default:
|
default:
|
||||||
setLocale('zh-CN')
|
setLocale('zh-CN')
|
||||||
return zhCN
|
return enUS
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ export default {
|
|||||||
},
|
},
|
||||||
chat: {
|
chat: {
|
||||||
newChatButton: 'New Chat',
|
newChatButton: 'New Chat',
|
||||||
placeholder: 'Ask me anything...(Shift + Enter = line break, "/" to trigger prompts)',
|
placeholder: 'Ask me anything...(Shift + Enter = line break)',
|
||||||
placeholderMobile: 'Ask me anything...',
|
placeholderMobile: 'Ask me anything...',
|
||||||
copy: 'Copy',
|
copy: 'Copy',
|
||||||
copied: 'Copied',
|
copied: 'Copied',
|
||||||
@@ -59,8 +59,6 @@ export default {
|
|||||||
name: 'Name',
|
name: 'Name',
|
||||||
description: 'Description',
|
description: 'Description',
|
||||||
role: 'Role',
|
role: 'Role',
|
||||||
temperature: 'Temperature',
|
|
||||||
top_p: 'Top_p',
|
|
||||||
resetUserInfo: 'Reset UserInfo',
|
resetUserInfo: 'Reset UserInfo',
|
||||||
chatHistory: 'ChatHistory',
|
chatHistory: 'ChatHistory',
|
||||||
theme: 'Theme',
|
theme: 'Theme',
|
||||||
@@ -71,7 +69,6 @@ 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',
|
siderButton: 'Prompt Store',
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import type { App } from 'vue'
|
import type { App } from 'vue'
|
||||||
import { createI18n } from 'vue-i18n'
|
import { createI18n } from 'vue-i18n'
|
||||||
import enUS from './en-US'
|
import enUS from './en-US'
|
||||||
import koKR from './ko-KR'
|
|
||||||
import zhCN from './zh-CN'
|
import zhCN from './zh-CN'
|
||||||
import zhTW from './zh-TW'
|
import zhTW from './zh-TW'
|
||||||
import ruRU from './ru-RU'
|
|
||||||
import { useAppStoreWithOut } from '@/store/modules/app'
|
import { useAppStoreWithOut } from '@/store/modules/app'
|
||||||
import type { Language } from '@/store/modules/app/helper'
|
import type { Language } from '@/store/modules/app/helper'
|
||||||
|
|
||||||
@@ -18,10 +16,8 @@ const i18n = createI18n({
|
|||||||
allowComposition: true,
|
allowComposition: true,
|
||||||
messages: {
|
messages: {
|
||||||
'en-US': enUS,
|
'en-US': enUS,
|
||||||
'ko-KR': koKR,
|
|
||||||
'zh-CN': zhCN,
|
'zh-CN': zhCN,
|
||||||
'zh-TW': zhTW,
|
'zh-TW': zhTW,
|
||||||
'ru-RU': ruRU,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -1,93 +0,0 @@
|
|||||||
export default {
|
|
||||||
common: {
|
|
||||||
add: '추가',
|
|
||||||
addSuccess: '추가 성공',
|
|
||||||
edit: '편집',
|
|
||||||
editSuccess: '편집 성공',
|
|
||||||
delete: '삭제',
|
|
||||||
deleteSuccess: '삭제 성공',
|
|
||||||
save: '저장',
|
|
||||||
saveSuccess: '저장 성공',
|
|
||||||
reset: '초기화',
|
|
||||||
action: '액션',
|
|
||||||
export: '내보내기',
|
|
||||||
exportSuccess: '내보내기 성공',
|
|
||||||
import: '가져오기',
|
|
||||||
importSuccess: '가져오기 성공',
|
|
||||||
clear: '비우기',
|
|
||||||
clearSuccess: '비우기 성공',
|
|
||||||
yes: '예',
|
|
||||||
no: '아니오',
|
|
||||||
confirm: '확인',
|
|
||||||
download: '다운로드',
|
|
||||||
noData: '데이터 없음',
|
|
||||||
wrong: '문제가 발생했습니다. 나중에 다시 시도하십시오.',
|
|
||||||
success: '성공',
|
|
||||||
failed: '실패',
|
|
||||||
verify: '검증',
|
|
||||||
unauthorizedTips: '인증되지 않았습니다. 먼저 확인하십시오.',
|
|
||||||
},
|
|
||||||
chat: {
|
|
||||||
newChatButton: '새로운 채팅',
|
|
||||||
placeholder: '무엇이든 물어보세요...(Shift + Enter = 줄바꿈, "/"를 눌러서 힌트를 보세요)',
|
|
||||||
placeholderMobile: '무엇이든 물어보세요...',
|
|
||||||
copy: '복사',
|
|
||||||
copied: '복사됨',
|
|
||||||
copyCode: '코드 복사',
|
|
||||||
clearChat: '채팅 비우기',
|
|
||||||
clearChatConfirm: '이 채팅을 비우시겠습니까?',
|
|
||||||
exportImage: '이미지 내보내기',
|
|
||||||
exportImageConfirm: '이 채팅을 png로 내보내시겠습니까?',
|
|
||||||
exportSuccess: '내보내기 성공',
|
|
||||||
exportFailed: '내보내기 실패',
|
|
||||||
usingContext: '컨텍스트 모드',
|
|
||||||
turnOnContext: '현재 모드에서는 이전 대화 기록을 포함하여 메시지를 보낼 수 있습니다.',
|
|
||||||
turnOffContext: '현재 모드에서는 이전 대화 기록을 포함하지 않고 메시지를 보낼 수 있습니다.',
|
|
||||||
deleteMessage: '메시지 삭제',
|
|
||||||
deleteMessageConfirm: '이 메시지를 삭제하시겠습니까?',
|
|
||||||
deleteHistoryConfirm: '이 기록을 삭제하시겠습니까?',
|
|
||||||
clearHistoryConfirm: '채팅 기록을 삭제하시겠습니까?',
|
|
||||||
preview: '미리보기',
|
|
||||||
showRawText: '원본 텍스트로 보기',
|
|
||||||
},
|
|
||||||
setting: {
|
|
||||||
setting: '설정',
|
|
||||||
general: '일반',
|
|
||||||
advanced: '고급',
|
|
||||||
config: '설정',
|
|
||||||
avatarLink: '아바타 링크',
|
|
||||||
name: '이름',
|
|
||||||
description: '설명',
|
|
||||||
role: '역할',
|
|
||||||
temperature: '온도',
|
|
||||||
top_p: 'Top_p',
|
|
||||||
resetUserInfo: '사용자 정보 초기화',
|
|
||||||
chatHistory: '채팅 기록',
|
|
||||||
theme: '테마',
|
|
||||||
language: '언어',
|
|
||||||
api: 'API',
|
|
||||||
reverseProxy: '리버스 프록시',
|
|
||||||
timeout: '타임아웃',
|
|
||||||
socks: 'Socks',
|
|
||||||
httpsProxy: 'HTTPS 프록시',
|
|
||||||
balance: 'API 잔액',
|
|
||||||
monthlyUsage: '월 사용량',
|
|
||||||
},
|
|
||||||
store: {
|
|
||||||
siderButton: '프롬프트 저장소',
|
|
||||||
local: '로컬',
|
|
||||||
online: '온라인',
|
|
||||||
title: '제목',
|
|
||||||
description: '설명',
|
|
||||||
clearStoreConfirm: '데이터를 삭제하시겠습니까?',
|
|
||||||
importPlaceholder: '여기에 JSON 데이터를 붙여넣으십시오',
|
|
||||||
addRepeatTitleTips: '제목 중복됨, 다시 입력하십시오',
|
|
||||||
addRepeatContentTips: '내용 중복됨: {msg}, 다시 입력하십시오',
|
|
||||||
editRepeatTitleTips: '제목 충돌, 수정하십시오',
|
|
||||||
editRepeatContentTips: '내용 충돌 {msg} , 수정하십시오',
|
|
||||||
importError: '키 값 불일치',
|
|
||||||
importRepeatTitle: '제목이 반복되어 건너뜀: {msg}',
|
|
||||||
importRepeatContent: '내용이 반복되어 건너뜀: {msg}',
|
|
||||||
onlineImportWarning: '참고: JSON 파일 소스를 확인하십시오!',
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
export default {
|
|
||||||
common: {
|
|
||||||
add: 'Добавить',
|
|
||||||
addSuccess: 'Добавлено успешно',
|
|
||||||
edit: 'Редактировать',
|
|
||||||
editSuccess: 'Изменено успешно',
|
|
||||||
delete: 'Удалить',
|
|
||||||
deleteSuccess: 'Удалено успешно',
|
|
||||||
save: 'Сохранить',
|
|
||||||
saveSuccess: 'Сохранено успешно',
|
|
||||||
reset: 'Сбросить',
|
|
||||||
action: 'Действие',
|
|
||||||
export: 'Экспортировать',
|
|
||||||
exportSuccess: 'Экспорт выполнен успешно',
|
|
||||||
import: 'Импортировать',
|
|
||||||
importSuccess: 'Импорт выполнен успешно',
|
|
||||||
clear: 'Очистить',
|
|
||||||
clearSuccess: 'Очищено успешно',
|
|
||||||
yes: 'Да',
|
|
||||||
no: 'Нет',
|
|
||||||
confirm: 'Подтвердить',
|
|
||||||
download: 'Загрузить',
|
|
||||||
noData: 'Нет данных',
|
|
||||||
wrong: 'Что-то пошло не так, пожалуйста, повторите попытку позже.',
|
|
||||||
success: 'Успех',
|
|
||||||
failed: 'Не удалось',
|
|
||||||
verify: 'Проверить',
|
|
||||||
unauthorizedTips: 'Не авторизован, сначала подтвердите свою личность.',
|
|
||||||
},
|
|
||||||
chat: {
|
|
||||||
newChatButton: 'Новый чат',
|
|
||||||
placeholder: 'Спросите меня о чем-нибудь ... (Shift + Enter = перенос строки, "/" для вызова подсказок)',
|
|
||||||
placeholderMobile: 'Спросите меня о чем-нибудь ...',
|
|
||||||
copy: 'Копировать',
|
|
||||||
copied: 'Скопировано',
|
|
||||||
copyCode: 'Копировать код',
|
|
||||||
clearChat: 'Очистить чат',
|
|
||||||
clearChatConfirm: 'Вы уверены, что хотите очистить этот чат?',
|
|
||||||
exportImage: 'Экспорт в изображение',
|
|
||||||
exportImageConfirm: 'Вы уверены, что хотите экспортировать этот чат в формате PNG?',
|
|
||||||
exportSuccess: 'Экспортировано успешно',
|
|
||||||
exportFailed: 'Не удалось выполнить экспорт',
|
|
||||||
usingContext: 'Режим контекста',
|
|
||||||
turnOnContext: 'В текущем режиме отправка сообщений будет включать предыдущие записи чата.',
|
|
||||||
turnOffContext: 'В текущем режиме отправка сообщений не будет включать предыдущие записи чата.',
|
|
||||||
deleteMessage: 'Удалить сообщение',
|
|
||||||
deleteMessageConfirm: 'Вы уверены, что хотите удалить это сообщение?',
|
|
||||||
deleteHistoryConfirm: 'Вы уверены, что хотите очистить эту историю?',
|
|
||||||
clearHistoryConfirm: 'Вы уверены, что хотите очистить историю чата?',
|
|
||||||
preview: 'Предварительный просмотр',
|
|
||||||
showRawText: 'Показать как обычный текст',
|
|
||||||
},
|
|
||||||
setting: {
|
|
||||||
setting: 'Настройки',
|
|
||||||
general: 'Общее',
|
|
||||||
advanced: 'Дополнительно',
|
|
||||||
config: 'Конфигурация',
|
|
||||||
avatarLink: 'Ссылка на аватар',
|
|
||||||
name: 'Имя',
|
|
||||||
description: 'Описание',
|
|
||||||
role: 'Роль',
|
|
||||||
temperature: 'Температура',
|
|
||||||
top_p: 'Top_p',
|
|
||||||
resetUserInfo: 'Сбросить информацию о пользователе',
|
|
||||||
chatHistory: 'История чата',
|
|
||||||
theme: 'Тема',
|
|
||||||
language: 'Язык',
|
|
||||||
api: 'API',
|
|
||||||
reverseProxy: 'Обратный прокси-сервер',
|
|
||||||
timeout: 'Время ожидания',
|
|
||||||
socks: 'Socks',
|
|
||||||
httpsProxy: 'HTTPS-прокси',
|
|
||||||
balance: 'Баланс API',
|
|
||||||
monthlyUsage: 'Ежемесячное использование',
|
|
||||||
},
|
|
||||||
store: {
|
|
||||||
siderButton: 'Хранилище подсказок',
|
|
||||||
local: 'Локальное',
|
|
||||||
online: 'Онлайн',
|
|
||||||
title: 'Название',
|
|
||||||
description: 'Описание',
|
|
||||||
clearStoreConfirm: 'Вы действительно хотите очистить данные?',
|
|
||||||
importPlaceholder: 'Пожалуйста, вставьте здесь JSON-данные',
|
|
||||||
addRepeatTitleTips: 'Дубликат названия, пожалуйста, введите другое название',
|
|
||||||
addRepeatContentTips: 'Дубликат содержимого: {msg}, пожалуйста, введите другой текст',
|
|
||||||
editRepeatTitleTips: 'Конфликт названий, пожалуйста, измените название',
|
|
||||||
editRepeatContentTips: 'Конфликт содержимого {msg}, пожалуйста, измените текст',
|
|
||||||
importError: 'Не совпадает ключ-значение',
|
|
||||||
importRepeatTitle: 'Название повторяющееся, пропускается: {msg}',
|
|
||||||
importRepeatContent: 'Содержание повторяющееся, пропускается: {msg}',
|
|
||||||
onlineImportWarning: 'Внимание! Проверьте источник JSON-файла!',
|
|
||||||
downloadError: 'Проверьте состояние сети и правильность JSON-файла',
|
|
||||||
},
|
|
||||||
}
|
|
||||||
@@ -29,7 +29,7 @@ export default {
|
|||||||
},
|
},
|
||||||
chat: {
|
chat: {
|
||||||
newChatButton: '新建聊天',
|
newChatButton: '新建聊天',
|
||||||
placeholder: '来说点什么吧...(Shift + Enter = 换行,"/" 触发提示词)',
|
placeholder: '来说点什么吧...(Shift + Enter = 换行)',
|
||||||
placeholderMobile: '来说点什么...',
|
placeholderMobile: '来说点什么...',
|
||||||
copy: '复制',
|
copy: '复制',
|
||||||
copied: '复制成功',
|
copied: '复制成功',
|
||||||
@@ -59,8 +59,6 @@ export default {
|
|||||||
name: '名称',
|
name: '名称',
|
||||||
description: '描述',
|
description: '描述',
|
||||||
role: '角色设定',
|
role: '角色设定',
|
||||||
temperature: 'Temperature',
|
|
||||||
top_p: 'Top_p',
|
|
||||||
resetUserInfo: '重置用户信息',
|
resetUserInfo: '重置用户信息',
|
||||||
chatHistory: '聊天记录',
|
chatHistory: '聊天记录',
|
||||||
theme: '主题',
|
theme: '主题',
|
||||||
@@ -71,7 +69,6 @@ export default {
|
|||||||
socks: 'Socks',
|
socks: 'Socks',
|
||||||
httpsProxy: 'HTTPS Proxy',
|
httpsProxy: 'HTTPS Proxy',
|
||||||
balance: 'API余额',
|
balance: 'API余额',
|
||||||
monthlyUsage: '本月使用量',
|
|
||||||
},
|
},
|
||||||
store: {
|
store: {
|
||||||
siderButton: '提示词商店',
|
siderButton: '提示词商店',
|
||||||
|
|||||||
@@ -28,8 +28,8 @@ export default {
|
|||||||
unauthorizedTips: '未經授權,請先進行驗證。',
|
unauthorizedTips: '未經授權,請先進行驗證。',
|
||||||
},
|
},
|
||||||
chat: {
|
chat: {
|
||||||
newChatButton: '新增對話',
|
newChatButton: '新建對話',
|
||||||
placeholder: '來說點什麼...(Shift + Enter = 換行,"/" 觸發提示詞)',
|
placeholder: '來說點什麼...(Shift + Enter = 換行)',
|
||||||
placeholderMobile: '來說點什麼...',
|
placeholderMobile: '來說點什麼...',
|
||||||
copy: '複製',
|
copy: '複製',
|
||||||
copied: '複製成功',
|
copied: '複製成功',
|
||||||
@@ -53,14 +53,12 @@ export default {
|
|||||||
setting: {
|
setting: {
|
||||||
setting: '設定',
|
setting: '設定',
|
||||||
general: '總覽',
|
general: '總覽',
|
||||||
advanced: '進階',
|
advanced: '高級',
|
||||||
config: '設定',
|
config: '設定',
|
||||||
avatarLink: '頭貼連結',
|
avatarLink: '頭貼連結',
|
||||||
name: '名稱',
|
name: '名稱',
|
||||||
description: '描述',
|
description: '描述',
|
||||||
role: '角色設定',
|
role: '角色設定',
|
||||||
temperature: 'Temperature',
|
|
||||||
top_p: 'Top_p',
|
|
||||||
resetUserInfo: '重設使用者資訊',
|
resetUserInfo: '重設使用者資訊',
|
||||||
chatHistory: '紀錄',
|
chatHistory: '紀錄',
|
||||||
theme: '主題',
|
theme: '主題',
|
||||||
@@ -70,8 +68,7 @@ export default {
|
|||||||
timeout: '逾時',
|
timeout: '逾時',
|
||||||
socks: 'Socks',
|
socks: 'Socks',
|
||||||
httpsProxy: 'HTTPS Proxy',
|
httpsProxy: 'HTTPS Proxy',
|
||||||
balance: 'API Credit 餘額',
|
balance: 'API余額',
|
||||||
monthlyUsage: '本月使用量',
|
|
||||||
},
|
},
|
||||||
store: {
|
store: {
|
||||||
siderButton: '提示詞商店',
|
siderButton: '提示詞商店',
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ const LOCAL_NAME = 'appSetting'
|
|||||||
|
|
||||||
export type Theme = 'light' | 'dark' | 'auto'
|
export type Theme = 'light' | 'dark' | 'auto'
|
||||||
|
|
||||||
export type Language = 'zh-CN' | 'zh-TW' | 'en-US' | 'ko-KR' | 'ru-RU'
|
export type Language = 'zh-CN' | 'zh-TW' | 'en-US'
|
||||||
|
|
||||||
export interface AppState {
|
export interface AppState {
|
||||||
siderCollapsed: boolean
|
siderCollapsed: boolean
|
||||||
|
|||||||
@@ -4,15 +4,12 @@ const LOCAL_NAME = 'settingsStorage'
|
|||||||
|
|
||||||
export interface SettingsState {
|
export interface SettingsState {
|
||||||
systemMessage: string
|
systemMessage: string
|
||||||
temperature: number
|
|
||||||
top_p: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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. Follow the user\'s instructions carefully. Respond using markdown.',
|
systemMessage: `You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.\nKnowledge cutoff: 2021-09-01\nCurrent date: ${currentDate}`,
|
||||||
temperature: 0.8,
|
|
||||||
top_p: 1,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ export function defaultSetting(): UserState {
|
|||||||
userInfo: {
|
userInfo: {
|
||||||
avatar: 'https://raw.githubusercontent.com/Chanzhaoyu/chatgpt-web/main/src/assets/avatar.jpg',
|
avatar: 'https://raw.githubusercontent.com/Chanzhaoyu/chatgpt-web/main/src/assets/avatar.jpg',
|
||||||
name: 'ChenZhaoYu',
|
name: 'ChenZhaoYu',
|
||||||
description: 'Star on <a href="https://github.com/Chanzhaoyu/chatgpt-bot" class="text-blue-500" target="_blank" >GitHub</a>',
|
description: 'Star on <a href="https://github.com/Chanzhaoyu/chatgpt-bot" class="text-blue-500" target="_blank" >Github</a>',
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -123,10 +123,7 @@ html {
|
|||||||
}
|
}
|
||||||
|
|
||||||
code.hljs {
|
code.hljs {
|
||||||
padding: 3px 5px;
|
padding: 3px 5px
|
||||||
&::-webkit-scrollbar {
|
|
||||||
height: 4px;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.hljs {
|
.hljs {
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
export function copyToClip(text: string) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
try {
|
|
||||||
const input: HTMLTextAreaElement = document.createElement('textarea')
|
|
||||||
input.setAttribute('readonly', 'readonly')
|
|
||||||
input.value = text
|
|
||||||
document.body.appendChild(input)
|
|
||||||
input.select()
|
|
||||||
if (document.execCommand('copy'))
|
|
||||||
document.execCommand('copy')
|
|
||||||
document.body.removeChild(input)
|
|
||||||
resolve(text)
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
reject(error)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
18
src/utils/crypto/index.ts
Normal file
18
src/utils/crypto/index.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import CryptoJS from 'crypto-js'
|
||||||
|
|
||||||
|
const CryptoSecret = '__CRYPTO_SECRET__'
|
||||||
|
|
||||||
|
export function enCrypto(data: any) {
|
||||||
|
const str = JSON.stringify(data)
|
||||||
|
return CryptoJS.AES.encrypt(str, CryptoSecret).toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deCrypto(data: string) {
|
||||||
|
const bytes = CryptoJS.AES.decrypt(data, CryptoSecret)
|
||||||
|
const str = bytes.toString(CryptoJS.enc.Utf8)
|
||||||
|
|
||||||
|
if (str)
|
||||||
|
return JSON.parse(str)
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
44
src/utils/format/index.ts
Normal file
44
src/utils/format/index.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
/**
|
||||||
|
* 转义 HTML 字符
|
||||||
|
* @param source
|
||||||
|
*/
|
||||||
|
export function encodeHTML(source: string) {
|
||||||
|
return source
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否为代码块
|
||||||
|
* @param text
|
||||||
|
*/
|
||||||
|
export function includeCode(text: string | null | undefined) {
|
||||||
|
const regexp = /^(?:\s{4}|\t).+/gm
|
||||||
|
return !!(text?.includes(' = ') || text?.match(regexp))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 复制文本
|
||||||
|
* @param options
|
||||||
|
*/
|
||||||
|
export function copyText(options: { text: string; origin?: boolean }) {
|
||||||
|
const props = { origin: true, ...options }
|
||||||
|
|
||||||
|
let input: HTMLInputElement | HTMLTextAreaElement
|
||||||
|
|
||||||
|
if (props.origin)
|
||||||
|
input = document.createElement('textarea')
|
||||||
|
else
|
||||||
|
input = document.createElement('input')
|
||||||
|
|
||||||
|
input.setAttribute('readonly', 'readonly')
|
||||||
|
input.value = props.text
|
||||||
|
document.body.appendChild(input)
|
||||||
|
input.select()
|
||||||
|
if (document.execCommand('copy'))
|
||||||
|
document.execCommand('copy')
|
||||||
|
document.body.removeChild(input)
|
||||||
|
}
|
||||||
@@ -1,57 +1 @@
|
|||||||
interface StorageData<T = any> {
|
export * from './local'
|
||||||
data: T
|
|
||||||
expire: number | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createLocalStorage(options?: { expire?: number | null }) {
|
|
||||||
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7
|
|
||||||
|
|
||||||
const { expire } = Object.assign({ expire: DEFAULT_CACHE_TIME }, options)
|
|
||||||
|
|
||||||
function set<T = any>(key: string, data: T) {
|
|
||||||
const storageData: StorageData<T> = {
|
|
||||||
data,
|
|
||||||
expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
|
|
||||||
}
|
|
||||||
|
|
||||||
const json = JSON.stringify(storageData)
|
|
||||||
window.localStorage.setItem(key, json)
|
|
||||||
}
|
|
||||||
|
|
||||||
function get(key: string) {
|
|
||||||
const json = window.localStorage.getItem(key)
|
|
||||||
if (json) {
|
|
||||||
let storageData: StorageData | null = null
|
|
||||||
|
|
||||||
try {
|
|
||||||
storageData = JSON.parse(json)
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
// Prevent failure
|
|
||||||
}
|
|
||||||
|
|
||||||
if (storageData) {
|
|
||||||
const { data, expire } = storageData
|
|
||||||
if (expire === null || expire >= Date.now())
|
|
||||||
return data
|
|
||||||
}
|
|
||||||
|
|
||||||
remove(key)
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function remove(key: string) {
|
|
||||||
window.localStorage.removeItem(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
function clear() {
|
|
||||||
window.localStorage.clear()
|
|
||||||
}
|
|
||||||
|
|
||||||
return { set, get, remove, clear }
|
|
||||||
}
|
|
||||||
|
|
||||||
export const ls = createLocalStorage()
|
|
||||||
|
|
||||||
export const ss = createLocalStorage({ expire: null })
|
|
||||||
|
|||||||
70
src/utils/storage/local.ts
Normal file
70
src/utils/storage/local.ts
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
import { deCrypto, enCrypto } from '../crypto'
|
||||||
|
|
||||||
|
interface StorageData<T = any> {
|
||||||
|
data: T
|
||||||
|
expire: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createLocalStorage(options?: { expire?: number | null; crypto?: boolean }) {
|
||||||
|
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7
|
||||||
|
|
||||||
|
const { expire, crypto } = Object.assign(
|
||||||
|
{
|
||||||
|
expire: DEFAULT_CACHE_TIME,
|
||||||
|
crypto: true,
|
||||||
|
},
|
||||||
|
options,
|
||||||
|
)
|
||||||
|
|
||||||
|
function set<T = any>(key: string, data: T) {
|
||||||
|
const storageData: StorageData<T> = {
|
||||||
|
data,
|
||||||
|
expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
|
||||||
|
}
|
||||||
|
|
||||||
|
const json = crypto ? enCrypto(storageData) : JSON.stringify(storageData)
|
||||||
|
window.localStorage.setItem(key, json)
|
||||||
|
}
|
||||||
|
|
||||||
|
function get(key: string) {
|
||||||
|
const json = window.localStorage.getItem(key)
|
||||||
|
if (json) {
|
||||||
|
let storageData: StorageData | null = null
|
||||||
|
|
||||||
|
try {
|
||||||
|
storageData = crypto ? deCrypto(json) : JSON.parse(json)
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
// Prevent failure
|
||||||
|
}
|
||||||
|
|
||||||
|
if (storageData) {
|
||||||
|
const { data, expire } = storageData
|
||||||
|
if (expire === null || expire >= Date.now())
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
remove(key)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function remove(key: string) {
|
||||||
|
window.localStorage.removeItem(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
function clear() {
|
||||||
|
window.localStorage.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
set,
|
||||||
|
get,
|
||||||
|
remove,
|
||||||
|
clear,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ls = createLocalStorage()
|
||||||
|
|
||||||
|
export const ss = createLocalStorage({ expire: null, crypto: false })
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed, onMounted, onUnmounted, onUpdated, ref } from 'vue'
|
import { computed, ref } from 'vue'
|
||||||
import MarkdownIt from 'markdown-it'
|
import MarkdownIt from 'markdown-it'
|
||||||
import mdKatex from '@traptitech/markdown-it-katex'
|
import mdKatex from '@traptitech/markdown-it-katex'
|
||||||
import mila from 'markdown-it-link-attributes'
|
import mila from 'markdown-it-link-attributes'
|
||||||
import hljs from 'highlight.js'
|
import hljs from 'highlight.js'
|
||||||
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||||
import { t } from '@/locales'
|
import { t } from '@/locales'
|
||||||
import { copyToClip } from '@/utils/copy'
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
inversion?: boolean
|
inversion?: boolean
|
||||||
@@ -23,7 +22,6 @@ const { isMobile } = useBasicLayout()
|
|||||||
const textRef = ref<HTMLElement>()
|
const textRef = ref<HTMLElement>()
|
||||||
|
|
||||||
const mdi = new MarkdownIt({
|
const mdi = new MarkdownIt({
|
||||||
html: false,
|
|
||||||
linkify: true,
|
linkify: true,
|
||||||
highlight(code, language) {
|
highlight(code, language) {
|
||||||
const validLang = !!(language && hljs.getLanguage(language))
|
const validLang = !!(language && hljs.getLanguage(language))
|
||||||
@@ -62,59 +60,23 @@ function highlightBlock(str: string, lang?: string) {
|
|||||||
return `<pre class="code-block-wrapper"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span><span class="code-block-header__copy">${t('chat.copyCode')}</span></div><code class="hljs code-block-body ${lang}">${str}</code></pre>`
|
return `<pre class="code-block-wrapper"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span><span class="code-block-header__copy">${t('chat.copyCode')}</span></div><code class="hljs code-block-body ${lang}">${str}</code></pre>`
|
||||||
}
|
}
|
||||||
|
|
||||||
function addCopyEvents() {
|
defineExpose({ textRef })
|
||||||
if (textRef.value) {
|
|
||||||
const copyBtn = textRef.value.querySelectorAll('.code-block-header__copy')
|
|
||||||
copyBtn.forEach((btn) => {
|
|
||||||
btn.addEventListener('click', () => {
|
|
||||||
const code = btn.parentElement?.nextElementSibling?.textContent
|
|
||||||
if (code) {
|
|
||||||
copyToClip(code).then(() => {
|
|
||||||
btn.textContent = '复制成功'
|
|
||||||
setTimeout(() => {
|
|
||||||
btn.textContent = '复制代码'
|
|
||||||
}, 1000)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeCopyEvents() {
|
|
||||||
if (textRef.value) {
|
|
||||||
const copyBtn = textRef.value.querySelectorAll('.code-block-header__copy')
|
|
||||||
copyBtn.forEach((btn) => {
|
|
||||||
btn.removeEventListener('click', () => {})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => {
|
|
||||||
addCopyEvents()
|
|
||||||
})
|
|
||||||
|
|
||||||
onUpdated(() => {
|
|
||||||
addCopyEvents()
|
|
||||||
})
|
|
||||||
|
|
||||||
onUnmounted(() => {
|
|
||||||
removeCopyEvents()
|
|
||||||
})
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="text-black" :class="wrapClass">
|
<div class="text-black" :class="wrapClass">
|
||||||
<div ref="textRef" class="leading-relaxed break-words">
|
<template v-if="loading">
|
||||||
<div v-if="!inversion">
|
<span class="dark:text-white w-[4px] h-[20px] block animate-blink" />
|
||||||
<div v-if="!asRawText" class="markdown-body" v-html="text" />
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<div ref="textRef" class="leading-relaxed break-words">
|
||||||
|
<div v-if="!inversion">
|
||||||
|
<div v-if="!asRawText" class="markdown-body" v-html="text" />
|
||||||
|
<div v-else class="whitespace-pre-wrap" v-text="text" />
|
||||||
|
</div>
|
||||||
<div v-else class="whitespace-pre-wrap" v-text="text" />
|
<div v-else class="whitespace-pre-wrap" v-text="text" />
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="whitespace-pre-wrap" v-text="text" />
|
</template>
|
||||||
<template v-if="loading">
|
|
||||||
<span class="dark:text-white w-[4px] h-[20px] block animate-blink" />
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
<script setup lang='ts'>
|
<script setup lang='ts'>
|
||||||
import { computed, ref } from 'vue'
|
import { computed, ref } from 'vue'
|
||||||
import { NDropdown, useMessage } from 'naive-ui'
|
import { NDropdown } from 'naive-ui'
|
||||||
import AvatarComponent from './Avatar.vue'
|
import AvatarComponent from './Avatar.vue'
|
||||||
import TextComponent from './Text.vue'
|
import TextComponent from './Text.vue'
|
||||||
import { SvgIcon } from '@/components/common'
|
import { SvgIcon } from '@/components/common'
|
||||||
|
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'
|
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||||
import { copyToClip } from '@/utils/copy'
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
dateTime?: string
|
dateTime?: string
|
||||||
@@ -30,8 +30,6 @@ const { isMobile } = useBasicLayout()
|
|||||||
|
|
||||||
const { iconRender } = useIconRender()
|
const { iconRender } = useIconRender()
|
||||||
|
|
||||||
const message = useMessage()
|
|
||||||
|
|
||||||
const textRef = ref<HTMLElement>()
|
const textRef = ref<HTMLElement>()
|
||||||
|
|
||||||
const asRawText = ref(props.inversion)
|
const asRawText = ref(props.inversion)
|
||||||
@@ -66,7 +64,7 @@ const options = computed(() => {
|
|||||||
function handleSelect(key: 'copyText' | 'delete' | 'toggleRenderType') {
|
function handleSelect(key: 'copyText' | 'delete' | 'toggleRenderType') {
|
||||||
switch (key) {
|
switch (key) {
|
||||||
case 'copyText':
|
case 'copyText':
|
||||||
handleCopy()
|
copyText({ text: props.text ?? '' })
|
||||||
return
|
return
|
||||||
case 'toggleRenderType':
|
case 'toggleRenderType':
|
||||||
asRawText.value = !asRawText.value
|
asRawText.value = !asRawText.value
|
||||||
@@ -80,16 +78,6 @@ function handleRegenerate() {
|
|||||||
messageRef.value?.scrollIntoView()
|
messageRef.value?.scrollIntoView()
|
||||||
emit('regenerate')
|
emit('regenerate')
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleCopy() {
|
|
||||||
try {
|
|
||||||
await copyToClip(props.text || '')
|
|
||||||
message.success('复制成功')
|
|
||||||
}
|
|
||||||
catch {
|
|
||||||
message.error('复制失败')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|||||||
24
src/views/chat/hooks/useCopyCode.ts
Normal file
24
src/views/chat/hooks/useCopyCode.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { onMounted, onUpdated } from 'vue'
|
||||||
|
import { copyText } from '@/utils/format'
|
||||||
|
|
||||||
|
export function useCopyCode() {
|
||||||
|
function copyCodeBlock() {
|
||||||
|
const codeBlockWrapper = document.querySelectorAll('.code-block-wrapper')
|
||||||
|
codeBlockWrapper.forEach((wrapper) => {
|
||||||
|
const copyBtn = wrapper.querySelector('.code-block-header__copy')
|
||||||
|
const codeBlock = wrapper.querySelector('.code-block-body')
|
||||||
|
if (copyBtn && codeBlock) {
|
||||||
|
copyBtn.addEventListener('click', () => {
|
||||||
|
if (navigator.clipboard?.writeText)
|
||||||
|
navigator.clipboard.writeText(codeBlock.textContent ?? '')
|
||||||
|
else
|
||||||
|
copyText({ text: codeBlock.textContent ?? '', origin: true })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => copyCodeBlock())
|
||||||
|
|
||||||
|
onUpdated(() => copyCodeBlock())
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import html2canvas from 'html2canvas'
|
|||||||
import { Message } from './components'
|
import { Message } from './components'
|
||||||
import { useScroll } from './hooks/useScroll'
|
import { useScroll } from './hooks/useScroll'
|
||||||
import { useChat } from './hooks/useChat'
|
import { useChat } from './hooks/useChat'
|
||||||
|
import { useCopyCode } from './hooks/useCopyCode'
|
||||||
import { useUsingContext } from './hooks/useUsingContext'
|
import { useUsingContext } from './hooks/useUsingContext'
|
||||||
import HeaderComponent from './components/Header/index.vue'
|
import HeaderComponent from './components/Header/index.vue'
|
||||||
import { HoverButton, SvgIcon } from '@/components/common'
|
import { HoverButton, SvgIcon } from '@/components/common'
|
||||||
@@ -26,6 +27,8 @@ const ms = useMessage()
|
|||||||
|
|
||||||
const chatStore = useChatStore()
|
const chatStore = useChatStore()
|
||||||
|
|
||||||
|
useCopyCode()
|
||||||
|
|
||||||
const { isMobile } = useBasicLayout()
|
const { isMobile } = useBasicLayout()
|
||||||
const { addChat, updateChat, updateChatSome, getChatByUuidAndIndex } = useChat()
|
const { addChat, updateChat, updateChatSome, getChatByUuidAndIndex } = useChat()
|
||||||
const { scrollRef, scrollToBottom, scrollToBottomIfAtBottom } = useScroll()
|
const { scrollRef, scrollToBottom, scrollToBottomIfAtBottom } = useScroll()
|
||||||
@@ -34,7 +37,7 @@ const { usingContext, toggleUsingContext } = useUsingContext()
|
|||||||
const { uuid } = route.params as { uuid: string }
|
const { uuid } = route.params as { uuid: string }
|
||||||
|
|
||||||
const dataSources = computed(() => chatStore.getChatByUuid(+uuid))
|
const dataSources = computed(() => chatStore.getChatByUuid(+uuid))
|
||||||
const conversationList = computed(() => dataSources.value.filter(item => (!item.inversion && !!item.conversationOptions)))
|
const conversationList = computed(() => dataSources.value.filter(item => (!item.inversion && !item.error)))
|
||||||
|
|
||||||
const prompt = ref<string>('')
|
const prompt = ref<string>('')
|
||||||
const loading = ref<boolean>(false)
|
const loading = ref<boolean>(false)
|
||||||
@@ -104,7 +107,9 @@ async function onConversation() {
|
|||||||
scrollToBottom()
|
scrollToBottom()
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let lastText = ''
|
const magicSplit = 't1h1i4s5i1s4a1s9i1l9l8y1s0plit'
|
||||||
|
let renderText = ''
|
||||||
|
let firstTime = true
|
||||||
const fetchChatAPIOnce = async () => {
|
const fetchChatAPIOnce = async () => {
|
||||||
await fetchChatAPIProcess<Chat.ConversationResponse>({
|
await fetchChatAPIProcess<Chat.ConversationResponse>({
|
||||||
prompt: message,
|
prompt: message,
|
||||||
@@ -114,43 +119,49 @@ async function onConversation() {
|
|||||||
const xhr = event.target
|
const xhr = event.target
|
||||||
const { responseText } = xhr
|
const { responseText } = xhr
|
||||||
// Always process the final line
|
// Always process the final line
|
||||||
const lastIndex = responseText.lastIndexOf('\n', responseText.length - 2)
|
|
||||||
let chunk = responseText
|
|
||||||
if (lastIndex !== -1)
|
|
||||||
chunk = responseText.substring(lastIndex)
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(chunk)
|
|
||||||
updateChat(
|
|
||||||
+uuid,
|
|
||||||
dataSources.value.length - 1,
|
|
||||||
{
|
|
||||||
dateTime: new Date().toLocaleString(),
|
|
||||||
text: lastText + (data.text ?? ''),
|
|
||||||
inversion: false,
|
|
||||||
error: false,
|
|
||||||
loading: true,
|
|
||||||
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
|
|
||||||
requestOptions: { prompt: message, options: { ...options } },
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
if (openLongReply && data.detail.choices[0].finish_reason === 'length') {
|
const splitIndexBegin = responseText.search(magicSplit)
|
||||||
options.parentMessageId = data.id
|
if (splitIndexBegin !== -1) {
|
||||||
lastText = data.text
|
const splitIndexEnd = splitIndexBegin + magicSplit.length
|
||||||
message = ''
|
|
||||||
return fetchChatAPIOnce()
|
const firstChunk = responseText.substring(0, splitIndexBegin)
|
||||||
|
const deltaText = responseText.substring(splitIndexEnd)
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(firstChunk)
|
||||||
|
if (firstTime) {
|
||||||
|
firstTime = false
|
||||||
|
renderText = data.text ?? ''
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
renderText = deltaText ?? ''
|
||||||
|
}
|
||||||
|
updateChat(
|
||||||
|
+uuid,
|
||||||
|
dataSources.value.length - 1,
|
||||||
|
{
|
||||||
|
dateTime: new Date().toLocaleString(),
|
||||||
|
text: renderText,
|
||||||
|
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
|
||||||
|
message = ''
|
||||||
|
return fetchChatAPIOnce()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
//
|
||||||
}
|
}
|
||||||
|
|
||||||
scrollToBottomIfAtBottom()
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
//
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
updateChatSome(+uuid, dataSources.value.length - 1, { loading: false })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await fetchChatAPIOnce()
|
await fetchChatAPIOnce()
|
||||||
}
|
}
|
||||||
catch (error: any) {
|
catch (error: any) {
|
||||||
@@ -230,12 +241,14 @@ async function onRegenerate(index: number) {
|
|||||||
error: false,
|
error: false,
|
||||||
loading: true,
|
loading: true,
|
||||||
conversationOptions: null,
|
conversationOptions: null,
|
||||||
requestOptions: { prompt: message, options: { ...options } },
|
requestOptions: { prompt: message, ...options },
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let lastText = ''
|
const magicSplit = 't1h1i4s5i1s4a1s9i1l9l8y1s0plit'
|
||||||
|
let renderText = ''
|
||||||
|
let firstTime = true
|
||||||
const fetchChatAPIOnce = async () => {
|
const fetchChatAPIOnce = async () => {
|
||||||
await fetchChatAPIProcess<Chat.ConversationResponse>({
|
await fetchChatAPIProcess<Chat.ConversationResponse>({
|
||||||
prompt: message,
|
prompt: message,
|
||||||
@@ -245,39 +258,48 @@ async function onRegenerate(index: number) {
|
|||||||
const xhr = event.target
|
const xhr = event.target
|
||||||
const { responseText } = xhr
|
const { responseText } = xhr
|
||||||
// Always process the final line
|
// Always process the final line
|
||||||
const lastIndex = responseText.lastIndexOf('\n', responseText.length - 2)
|
|
||||||
let chunk = responseText
|
|
||||||
if (lastIndex !== -1)
|
|
||||||
chunk = responseText.substring(lastIndex)
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(chunk)
|
|
||||||
updateChat(
|
|
||||||
+uuid,
|
|
||||||
index,
|
|
||||||
{
|
|
||||||
dateTime: new Date().toLocaleString(),
|
|
||||||
text: lastText + (data.text ?? ''),
|
|
||||||
inversion: false,
|
|
||||||
error: false,
|
|
||||||
loading: true,
|
|
||||||
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
|
|
||||||
requestOptions: { prompt: message, options: { ...options } },
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
if (openLongReply && data.detail.choices[0].finish_reason === 'length') {
|
const splitIndexBegin = responseText.search(magicSplit)
|
||||||
options.parentMessageId = data.id
|
if (splitIndexBegin !== -1) {
|
||||||
lastText = data.text
|
const splitIndexEnd = splitIndexBegin + magicSplit.length
|
||||||
message = ''
|
|
||||||
return fetchChatAPIOnce()
|
const firstChunk = responseText.substring(0, splitIndexBegin)
|
||||||
|
const deltaText = responseText.substring(splitIndexEnd)
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(firstChunk)
|
||||||
|
if (firstTime) {
|
||||||
|
firstTime = false
|
||||||
|
renderText = data.text ?? ''
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
renderText = deltaText ?? ''
|
||||||
|
}
|
||||||
|
updateChat(
|
||||||
|
+uuid,
|
||||||
|
index,
|
||||||
|
{
|
||||||
|
dateTime: new Date().toLocaleString(),
|
||||||
|
text: renderText,
|
||||||
|
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
|
||||||
|
message = ''
|
||||||
|
return fetchChatAPIOnce()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
//
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
//
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
updateChatSome(+uuid, index, { loading: false })
|
|
||||||
}
|
}
|
||||||
await fetchChatAPIOnce()
|
await fetchChatAPIOnce()
|
||||||
}
|
}
|
||||||
@@ -305,7 +327,7 @@ async function onRegenerate(index: number) {
|
|||||||
error: true,
|
error: true,
|
||||||
loading: false,
|
loading: false,
|
||||||
conversationOptions: null,
|
conversationOptions: null,
|
||||||
requestOptions: { prompt: message, options: { ...options } },
|
requestOptions: { prompt: message, ...options },
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -466,16 +488,13 @@ onUnmounted(() => {
|
|||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col w-full h-full">
|
<div class="flex flex-col w-full h-full">
|
||||||
<HeaderComponent
|
<HeaderComponent
|
||||||
v-if="isMobile"
|
v-if="isMobile" :using-context="usingContext" @export="handleExport"
|
||||||
:using-context="usingContext"
|
|
||||||
@export="handleExport"
|
|
||||||
@toggle-using-context="toggleUsingContext"
|
@toggle-using-context="toggleUsingContext"
|
||||||
/>
|
/>
|
||||||
<main class="flex-1 overflow-hidden">
|
<main class="flex-1 overflow-hidden">
|
||||||
<div id="scrollRef" ref="scrollRef" class="h-full overflow-hidden overflow-y-auto">
|
<div 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]"
|
|
||||||
:class="[isMobile ? 'p-2' : 'p-4']"
|
:class="[isMobile ? 'p-2' : 'p-4']"
|
||||||
>
|
>
|
||||||
<template v-if="!dataSources.length">
|
<template v-if="!dataSources.length">
|
||||||
@@ -487,14 +506,8 @@ onUnmounted(() => {
|
|||||||
<template v-else>
|
<template v-else>
|
||||||
<div>
|
<div>
|
||||||
<Message
|
<Message
|
||||||
v-for="(item, index) of dataSources"
|
v-for="(item, index) of dataSources" :key="index" :date-time="item.dateTime" :text="item.text"
|
||||||
:key="index"
|
:inversion="item.inversion" :error="item.error" :loading="item.loading" @regenerate="onRegenerate(index)"
|
||||||
:date-time="item.dateTime"
|
|
||||||
:text="item.text"
|
|
||||||
:inversion="item.inversion"
|
|
||||||
:error="item.error"
|
|
||||||
:loading="item.loading"
|
|
||||||
@regenerate="onRegenerate(index)"
|
|
||||||
@delete="handleDelete(index)"
|
@delete="handleDelete(index)"
|
||||||
/>
|
/>
|
||||||
<div class="sticky bottom-0 left-0 flex justify-center">
|
<div class="sticky bottom-0 left-0 flex justify-center">
|
||||||
@@ -531,15 +544,9 @@ onUnmounted(() => {
|
|||||||
<NAutoComplete v-model:value="prompt" :options="searchOptions" :render-label="renderOption">
|
<NAutoComplete v-model:value="prompt" :options="searchOptions" :render-label="renderOption">
|
||||||
<template #default="{ handleInput, handleBlur, handleFocus }">
|
<template #default="{ handleInput, handleBlur, handleFocus }">
|
||||||
<NInput
|
<NInput
|
||||||
ref="inputRef"
|
ref="inputRef" v-model:value="prompt" type="textarea" :placeholder="placeholder"
|
||||||
v-model:value="prompt"
|
:autosize="{ minRows: 1, maxRows: isMobile ? 4 : 8 }" @input="handleInput" @focus="handleFocus"
|
||||||
type="textarea"
|
@blur="handleBlur" @keypress="handleEnter"
|
||||||
:placeholder="placeholder"
|
|
||||||
:autosize="{ minRows: 1, maxRows: isMobile ? 4 : 8 }"
|
|
||||||
@input="handleInput"
|
|
||||||
@focus="handleFocus"
|
|
||||||
@blur="handleBlur"
|
|
||||||
@keypress="handleEnter"
|
|
||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
</NAutoComplete>
|
</NAutoComplete>
|
||||||
|
|||||||
Reference in New Issue
Block a user