Compare commits

...

69 Commits

Author SHA1 Message Date
ChenZhaoYu
a7c97026b7 chore: v2.10.9 2023-04-03 09:46:46 +08:00
ChenZhaoYu
0ff7825387 chore: update README.md 2023-04-03 09:21:08 +08:00
ChenZhaoYu
c2b25a84c7 chore: default API_REVERSE_PROXY 2023-04-03 09:19:12 +08:00
ChenZhaoYu
553e239db3 chore: update .env.examples 2023-04-03 09:01:56 +08:00
idawnwon
e3a3e4dc29 fix: Update @acheong08 Reverse Proxy URL (#1085) 2023-04-03 08:53:52 +08:00
ChenZhaoYu
4e4e41b0d6 chore: update deps 2023-04-03 08:51:04 +08:00
vchenpeng
5594b0baa9 fix: 空引用显示undefined (#1103)
Co-authored-by: peng.chen <peng.chen@freemud.com>
2023-04-03 08:48:59 +08:00
Fog3211
e2ad3fe248 fix: x-scrollbar height (#1153)
Co-authored-by: Fog3211 <23151576+Fog3211@users.noreply.github.com>
2023-04-03 08:25:07 +08:00
ChenZhaoYu
9bd88eac84 fix: 宽度问题 2023-03-31 14:52:54 +08:00
ChenZhaoYu
431de382dc perf: input auto size 2023-03-31 14:43:40 +08:00
ChenZhaoYu
b241240fc6 perf: 默认 systemMessage 2023-03-31 13:42:16 +08:00
ChenZhaoYu
40fa028408 fix: some error 2023-03-31 13:37:07 +08:00
ChenZhaoYu
15f3aac88e perf: 调整光标位置 2023-03-31 13:20:55 +08:00
Hank
90f0c3a80b feat: add socks username/password config (#890)
Co-authored-by: Redon <790348264@qq.com>
2023-03-31 13:09:51 +08:00
ChenZhaoYu
d2a852d5eb chore: .eslintignore 2023-03-31 13:05:30 +08:00
yimiaoxiehou
85543deca3 feat: 添加 socks5 代理认证 (#999)
* support socks5 proxy auth

* Update build_docker.yml

* Update README.md

* perf: 增加判断

* fix: lint

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-31 12:23:26 +08:00
ChenZhaoYu
142759ac50 chore: lint fix 2023-03-31 11:53:10 +08:00
Miku
da20aed4b0 feat: add kubernetes deploy (#1001) 2023-03-31 11:52:10 +08:00
puppywang
c0f4af05e3 feat: add typing effect (#1017)
* feat: add typing effect

* fix: ts2339 xxx not exist on type 'never'

---------

Co-authored-by: WangYi <wangyi@windimg.com>
2023-03-31 11:50:32 +08:00
cong
468bed7705 feat: allow user disable openai API debug log (#1041)
* feat: allow user disable openai API debug log

* chore: fix pnpm lock
2023-03-31 11:40:01 +08:00
LOVECHEN
0878af0239 perf: 加入容器名字 (#1035)
这样查看服务的时候会更优雅
2023-03-31 11:34:31 +08:00
ChenZhaoYu
aa0487edc4 chore: gitHub action 2023-03-29 16:21:08 +08:00
ChenZhaoYu
76cef650b4 chore: build rollback 2023-03-28 16:06:11 +08:00
assassinliujie
78bcf7f4ce perf: optimized output (#962)
* Update index.ts

* Update index.vue

* Update index.ts
2023-03-28 15:47:40 +08:00
ChenZhaoYu
c0a9fd5208 fix: 快速按下删除会话导致的问题 #917 2023-03-28 13:48:49 +08:00
ChenZhaoYu
07123b70ad chore: rolled back to clear the impact 2023-03-28 13:20:55 +08:00
assassinliujie
b579d24d19 pref: message output optimization (#935)
* Update index.ts

修改后端,让保留打字机效果的同时优化前后端之间传输的内容,节省流量和性能

* Update index.vue

修改前端,和之前修改的后端匹配,保留打字机效果同时优化性能和流量传输

* chore: lint fix

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-28 09:40:20 +08:00
KingTwinkle
e2eeee455a fix: local import error and NModal not as expected (#938) 2023-03-28 09:34:15 +08:00
weifeng
32ad20416c chore: Update README.md (#880)
* Update README.md

docker-compose 文件中注释掉未使用的配置节点,因为 留xxx 会导代码读取节点内容值为xxx,而不是期望的默认值,导致代码运行异常
增加 对模型可选参数的备注

* style: eslint fix

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-27 15:58:54 +08:00
吴杉(Shan Wu)
799af86739 perf: add localization for sider (#911) 2023-03-27 15:49:42 +08:00
ChenZhaoYu
c3f431118b chore: update docs 2023-03-26 10:08:01 +08:00
zaimoe
a3944f86b7 fix: missing VITE_GLOB_API_URL when docker build, fixed #690 #717 # (#877) 2023-03-25 17:23:57 +08:00
Yige
365a7df1ff Merge pull request #883 from yi-ge/dev-main
docs: 更新README.md,添加长回复使用方法
2023-03-25 17:06:20 +08:00
yi-ge
639152f987 docs: update README.md, add long reply feature 2023-03-25 17:01:12 +08:00
gitgitgogogo
fb8ad3790d fix: 反向代理限流失效 (#863)
https://docs.colyseus.io/zh_hk/colyseus/how-to/rate-limit/

使用nginx限流会只识别为服务器ip,需启用trust proxy
2023-03-25 08:30:15 +08:00
ChenZhaoYu
902321026b perf: 本地地址 2023-03-24 08:14:51 +08:00
ChenZhaoYu
9b0d7dbee8 fix: 移动端焦点不触发的问题 2023-03-23 21:12:36 +08:00
ChenZhaoYu
634c879108 perf: 自动焦点时移动端上的不便 2023-03-23 20:51:20 +08:00
Kid
57a1d6e3cd fix: ESM error (#826) 2023-03-23 20:43:47 +08:00
ChenZhaoYu
9081b22ce9 perf: 移动端删除 chat 时,侧边栏应该收起 2023-03-23 16:56:59 +08:00
Redon
73e12b1fdd fix: 移动端新建会话关闭侧边栏 (#813) 2023-03-23 16:23:57 +08:00
Bing
5fca2e9fa3 fix: PWA 未添加的问题 (#807)
Co-authored-by: bingo235 <>
2023-03-23 15:55:51 +08:00
ChenZhaoYu
917feec5d8 fix: 重置时应该移除本地储存 2023-03-23 14:50:36 +08:00
ChenZhaoYu
c52195cef8 chore: v2.10.8 2023-03-23 14:26:37 +08:00
ChenZhaoYu
630e88b8c4 fix: prompt store 样式问题 2023-03-23 14:04:06 +08:00
Peter Dave Hello
734eb7a3fb feat: add zh-TW prompts in the Promt Store (#796) 2023-03-23 13:57:26 +08:00
东子
e55fc06686 docs: fix docker port to private (#802) 2023-03-23 13:56:52 +08:00
ChenZhaoYu
5fee11323b perf: 网络连接时 500 自动跳转到主页 2023-03-22 20:01:39 +08:00
Allen
814c3a2565 feat: 切换 history 时自动聚焦输入框 (#735)
* feat: 修改 scrollToBottom 行为(当滚动条在底部或发送问题时才会进入自动滚动,滚轮向上滚动会中止自动滚动,方便复制和查看之前的代码; 切换 history 时自动聚焦输入框,方便直接输入文字,不用再次去点击输入框;)

* chore: 通过eslint检查

* perf: 清理重复功能

---------

Co-authored-by: Redon <790348264@qq.com>
2023-03-22 19:53:21 +08:00
ChenZhaoYu
d2a22a3ee5 feat: PWA 默认不开启 2023-03-22 19:42:40 +08:00
Yi
92278932ef chore: 显示原文时使用 .whitespace-pre-wrap (#779)
显示 ChatGPT 输出的原文时保留空格和换行
2023-03-22 19:42:01 +08:00
hncboy
9c6a3d6110 feat: 增加 ChatGPTUnofficialProxyAPI 的模型自定义配置 (#632)
* feat: 增加 ChatGPTUnofficialProxyAPI 的模型自定义配置(#618)

* perf: 修改判断

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-22 19:00:58 +08:00
Liut
e30217542d fix line end with new-line in some backend (#474)
* fix line end with new-line in some backend

In backend with golang (like https://github.com/sashabaranov/go-openai), the responseText always has '\n'.

* feat: 补全遗漏

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-22 18:49:40 +08:00
KeepRunning
1edf591721 chore(vsc-debug): 增加 visual-studio-code 的 debug 启动文件 (#296) 2023-03-22 18:35:10 +08:00
vulgate
60fd2ae0e0 feat: Create start.cmd (#656)
在windows下也可以运行
2023-03-22 18:31:52 +08:00
吴杉(Shan Wu)
3e509f6663 feat: 当用gpt-4的API 时增加可用的 Max Tokens (#729)
* fix: 用GPT-4 API时增加max token

* style: eslint fix

---------

Co-authored-by: Redon <790348264@qq.com>
2023-03-22 18:31:04 +08:00
ChenZhaoYu
bf48eae9fe feat: 更新依赖并兼容已存在的代理 2023-03-22 18:23:31 +08:00
舜岳
31a84325d4 perf: scrollToBottom 改成 scrollToBottomIfAtBottom (#771) 2023-03-22 18:00:53 +08:00
舜岳
b1d0056429 perf: 重置回答时滚动定位至该回答 (#781)
* chore: 重置回答时滚动定位至该回答

* perf: format code

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-22 17:54:29 +08:00
quzard
6ecc61ac5d feat: 添加角色设定预留API 设定页(#768)
* add systemMessage

* perf: 优化代码和类型

* perf: 补全翻译和为以后做准备

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-22 17:47:07 +08:00
xiaozhu
e02ab1fbad feat: 新增限流功能 (#718)
* 请求速率限制

* perf: 优化代码

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-21 09:20:27 +08:00
Yi
47dc009505 feat: 添加用于显示回复消息原文的选项 (#672)
* feat: 添加显示用于原文的选项

* chore: 修复暗色主题下文本颜色问题

给输入和输出气泡添加了 css 类,用来处理在暗色主题下聊天气泡的文本颜色

* feat: 用户输入不应该被渲染,防止 xss

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
2023-03-21 08:44:40 +08:00
ChenZhaoYu
f1584b60e8 fix: 手动重置异常的 loading 2023-03-19 18:12:49 +08:00
ChenZhaoYu
d1c15f58c4 perf: config 接口添加权限验证 2023-03-19 12:31:14 +08:00
ChenZhaoYu
d422a805f6 feat: 渲染的链接新窗口打开 2023-03-17 16:06:55 +08:00
ChenZhaoYu
08b5772420 feat: 查询余额使用 API_BASE_URL 参数 2023-03-17 13:19:03 +08:00
ChenZhaoYu
8fad91ade7 chore: v2.10.7 2023-03-17 11:43:42 +08:00
ChenZhaoYu
560378fd45 fix: 添加 usingContext 缺省 2023-03-17 11:40:05 +08:00
ChenZhaoYu
95ce026813 fix: 回退 chatgpt 版本导致的代理失效 2023-03-17 11:37:33 +08:00
50 changed files with 2526 additions and 2232 deletions

View File

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

5
.env
View File

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

2
.eslintignore Normal file
View File

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

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

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

25
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,25 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Web App",
"url": "http://localhost:1002",
"webRoot": "${workspaceFolder}"
},
{
"type": "node",
"request": "launch",
"name": "Launch Service Server",
"runtimeExecutable": "${workspaceFolder}/service/node_modules/.bin/esno",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/service/src/index.ts",
"outFiles": ["${workspaceFolder}/service/**/*.js"],
"envFile": "${workspaceFolder}/service/.env"
}
]
}

View File

@@ -37,6 +37,7 @@
"linkify",
"logprobs",
"mdhljs",
"mila",
"nodata",
"OPENAI",
"pinia",

View File

@@ -1,3 +1,77 @@
## v2.10.9
`2023-04-03`
> 更新默认 `accessToken` 反代地址为 [[acheong08](https://github.com/acheong08)] 的 `https://bypass.churchless.tech/api/conversation`
## Enhancement
- 添加 `socks5` 代理认证 [[yimiaoxiehou](https://github.com/Chanzhaoyu/chatgpt-web/pull/999)]
- 添加 `socks` 代理用户名密码的配置 [[hank-cp](https://github.com/Chanzhaoyu/chatgpt-web/pull/890)]
- 添加可选日志打印 [[zcong1993](https://github.com/Chanzhaoyu/chatgpt-web/pull/1041)]
- 更新侧边栏按钮本地化[[simonwu53](https://github.com/Chanzhaoyu/chatgpt-web/pull/911)]
- 优化代码块滚动条高度 [[Fog3211](https://github.com/Chanzhaoyu/chatgpt-web/pull/1153)]
## BugFix
- 修复 `PWA` 问题 [[bingo235](https://github.com/Chanzhaoyu/chatgpt-web/pull/807)]
- 修复 `ESM` 错误 [[kidonng](https://github.com/Chanzhaoyu/chatgpt-web/pull/826)]
- 修复反向代理开启时限流失效的问题 [[gitgitgogogo](https://github.com/Chanzhaoyu/chatgpt-web/pull/863)]
- 修复 `docker` 构建时 `.env` 可能被忽略的问题 [[zaiMoe](https://github.com/Chanzhaoyu/chatgpt-web/pull/877)]
- 修复导出异常错误 [[KingTwinkle](https://github.com/Chanzhaoyu/chatgpt-web/pull/938)]
- 修复空值异常 [[vchenpeng](https://github.com/Chanzhaoyu/chatgpt-web/pull/1103)]
- 移动端上的体验问题
## Other
- `Docker` 容器名字名义 [[LOVECHEN](https://github.com/Chanzhaoyu/chatgpt-web/pull/1035)]
- `kubernetes` 部署配置 [[CaoYunzhou](https://github.com/Chanzhaoyu/chatgpt-web/pull/1001)]
- 感谢 [[assassinliujie](https://github.com/Chanzhaoyu/chatgpt-web/pull/962)] 和 [[puppywang](https://github.com/Chanzhaoyu/chatgpt-web/pull/1017)] 的某些贡献
- 更新 `kubernetes/deploy.yaml` [[idawnwon](https://github.com/Chanzhaoyu/chatgpt-web/pull/1085)]
- 文档更新 [[#yi-ge](https://github.com/Chanzhaoyu/chatgpt-web/pull/883)]
- 文档更新 [[weifeng12x](https://github.com/Chanzhaoyu/chatgpt-web/pull/880)]
- 依赖更新
## v2.10.8
`2023-03-23`
如遇问题,请删除 `node_modules` 重新安装依赖。
## Feature
- 显示回复消息原文的选项 [[yilozt](https://github.com/Chanzhaoyu/chatgpt-web/pull/672)]
- 添加单 `IP` 每小时请求限制。环境变量: `MAX_REQUEST_PER_HOUR` [[zhuxindong ](https://github.com/Chanzhaoyu/chatgpt-web/pull/718)]
- 前端添加角色设定,仅 `API` 方式可见 [[quzard](https://github.com/Chanzhaoyu/chatgpt-web/pull/768)]
- `OPENAI_API_MODEL` 变量现在对 `ChatGPTUnofficialProxyAPI` 也生效,注意:`Token``API` 的模型命名不一致,不能直接填入 `gpt-3.5` 或者 `gpt-4` [[hncboy](https://github.com/Chanzhaoyu/chatgpt-web/pull/632)]
- 添加繁体中文 `Prompts` [[PeterDaveHello](https://github.com/Chanzhaoyu/chatgpt-web/pull/796)]
## Enhancement
- 重置回答时滚动定位至该回答 [[shunyue1320](https://github.com/Chanzhaoyu/chatgpt-web/pull/781)]
-`API``gpt-4` 时增加可用的 `Max Tokens` [[simonwu53](https://github.com/Chanzhaoyu/chatgpt-web/pull/729)]
- 判断和忽略回复字符 [[liut](https://github.com/Chanzhaoyu/chatgpt-web/pull/474)]
- 切换会话时,自动聚焦输入框 [[JS-an](https://github.com/Chanzhaoyu/chatgpt-web/pull/735)]
- 渲染的链接新窗口打开
- 查询余额可选 `API_BASE_URL` 代理地址
- `config` 接口添加验证防止被无限制调用
- `PWA` 默认不开启,现在需手动修改 `.env` 文件 `VITE_GLOB_APP_PWA` 变量
- 当网络连接时,刷新页面,`500` 错误页自动跳转到主页
## BugFix
- `scrollToBottom` 调回 `scrollToBottomIfAtBottom` [[shunyue1320](https://github.com/Chanzhaoyu/chatgpt-web/pull/771)]
- 重置异常的 `loading` 会话
## Common
- 创建 `start.cmd``windows` 下也可以运行 [vulgatecnn](https://github.com/Chanzhaoyu/chatgpt-web/pull/656)]
- 添加 `visual-studio-code` 中调试配置 [[ChandlerVer5](https://github.com/Chanzhaoyu/chatgpt-web/pull/296)]
- 修复文档中 `docker` 端口为本地 [[kilvn](https://github.com/Chanzhaoyu/chatgpt-web/pull/802)]
## Other
- 依赖更新
## v2.10.7
`2023-03-17`
## BugFix
- 回退 `chatgpt` 版本,原因:导致 `OPENAI_API_BASE_URL` 代理失效
- 修复缺省状态的 `usingContext` 默认值
## v2.10.6
`2023-03-17`

View File

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

View File

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

View File

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

9
kubernetes/README.md Normal file
View File

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

66
kubernetes/deploy.yaml Normal file
View File

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

21
kubernetes/ingress.yaml Normal file
View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "chatgpt-web",
"version": "2.10.6",
"version": "2.10.9",
"private": false,
"description": "ChatGPT Web",
"author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>",
@@ -43,6 +43,7 @@
"@types/crypto-js": "^4.1.1",
"@types/katex": "^0.16.0",
"@types/markdown-it": "^12.2.3",
"@types/markdown-it-link-attributes": "^3.0.1",
"@types/node": "^18.14.6",
"@vitejs/plugin-vue": "^4.0.0",
"autoprefixer": "^10.4.13",
@@ -52,6 +53,7 @@
"husky": "^8.0.3",
"less": "^4.1.3",
"lint-staged": "^13.1.2",
"markdown-it-link-attributes": "^4.0.1",
"npm-run-all": "^4.1.5",
"postcss": "^8.4.21",
"rimraf": "^4.2.0",

2333
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -16,7 +16,7 @@
"scripts": {
"start": "esno ./src/index.ts",
"dev": "esno watch ./src/index.ts",
"prod": "esno ./build/index.js",
"prod": "node ./build/index.mjs",
"build": "pnpm clean && tsup",
"clean": "rimraf build",
"lint": "eslint .",
@@ -25,10 +25,11 @@
},
"dependencies": {
"axios": "^1.3.4",
"chatgpt": "^5.1.1",
"chatgpt": "^5.2.2",
"dotenv": "^16.0.3",
"esno": "^0.16.3",
"express": "^4.18.2",
"express-rate-limit": "^6.7.0",
"https-proxy-agent": "^5.0.1",
"isomorphic-fetch": "^3.0.0",
"node-fetch": "^3.3.0",

1240
service/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,12 +3,17 @@ import 'isomorphic-fetch'
import type { ChatGPTAPIOptions, ChatMessage, SendMessageOptions } from 'chatgpt'
import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt'
import { SocksProxyAgent } from 'socks-proxy-agent'
import { HttpsProxyAgent } from 'https-proxy-agent'
import httpsProxyAgent from 'https-proxy-agent'
import fetch from 'node-fetch'
import axios from 'axios'
import { sendResponse } from '../utils'
import { isNotEmptyString } from '../utils/is'
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
import type { RequestOptions } from './types'
const { HttpsProxyAgent } = httpsProxyAgent
dotenv.config()
const ErrorCodeMessage: Record<string, string> = {
401: '[OpenAI] 提供错误的API密钥 | Incorrect API key provided',
@@ -19,13 +24,12 @@ const ErrorCodeMessage: Record<string, string> = {
500: '[OpenAI] 服务器繁忙,请稍后再试 | Internal Server Error',
}
dotenv.config()
const timeoutMs: number = !isNaN(+process.env.TIMEOUT_MS) ? +process.env.TIMEOUT_MS : 30 * 1000
const disableDebug: boolean = process.env.OPENAI_API_DISABLE_DEBUG === 'true'
let apiModel: ApiModel
if (!process.env.OPENAI_API_KEY && !process.env.OPENAI_ACCESS_TOKEN)
if (!isNotEmptyString(process.env.OPENAI_API_KEY) && !isNotEmptyString(process.env.OPENAI_ACCESS_TOKEN))
throw new Error('Missing OPENAI_API_KEY or OPENAI_ACCESS_TOKEN environment variable')
let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
@@ -33,18 +37,32 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
(async () => {
// More Info: https://github.com/transitive-bullshit/chatgpt-api
if (process.env.OPENAI_API_KEY) {
if (isNotEmptyString(process.env.OPENAI_API_KEY)) {
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL
const OPENAI_API_MODEL = process.env.OPENAI_API_MODEL
const model = isNotEmptyString(OPENAI_API_MODEL) ? OPENAI_API_MODEL : 'gpt-3.5-turbo'
const options: ChatGPTAPIOptions = {
apiKey: process.env.OPENAI_API_KEY,
completionParams: { model },
debug: true,
debug: !disableDebug,
}
if (isNotEmptyString(process.env.OPENAI_API_BASE_URL))
options.apiBaseUrl = process.env.OPENAI_API_BASE_URL
// increase max token limit if use gpt-4
if (model.toLowerCase().includes('gpt-4')) {
// if use 32k model
if (model.toLowerCase().includes('32k')) {
options.maxModelTokens = 32768
options.maxResponseTokens = 8192
}
else {
options.maxModelTokens = 8192
options.maxResponseTokens = 2048
}
}
if (isNotEmptyString(OPENAI_API_BASE_URL))
options.apiBaseUrl = `${OPENAI_API_BASE_URL}/v1`
setupProxy(options)
@@ -52,13 +70,18 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
apiModel = 'ChatGPTAPI'
}
else {
const OPENAI_API_MODEL = process.env.OPENAI_API_MODEL
const options: ChatGPTUnofficialProxyAPIOptions = {
accessToken: process.env.OPENAI_ACCESS_TOKEN,
debug: true,
debug: !disableDebug,
}
if (isNotEmptyString(process.env.API_REVERSE_PROXY))
options.apiReverseProxyUrl = process.env.API_REVERSE_PROXY
if (isNotEmptyString(OPENAI_API_MODEL))
options.model = OPENAI_API_MODEL
options.apiReverseProxyUrl = isNotEmptyString(process.env.API_REVERSE_PROXY)
? process.env.API_REVERSE_PROXY
: 'https://bypass.churchless.tech/api/conversation'
setupProxy(options)
@@ -67,17 +90,19 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
}
})()
async function chatReplyProcess(
message: string,
lastContext?: { conversationId?: string; parentMessageId?: string },
process?: (chat: ChatMessage) => void,
) {
async function chatReplyProcess(options: RequestOptions) {
const { message, lastContext, process, systemMessage } = options
try {
let options: SendMessageOptions = { timeoutMs }
if (lastContext) {
if (apiModel === 'ChatGPTAPI') {
if (isNotEmptyString(systemMessage))
options.systemMessage = systemMessage
}
if (lastContext != null) {
if (apiModel === 'ChatGPTAPI')
options = { parentMessageId: lastContext.parentMessageId }
options.parentMessageId = lastContext.parentMessageId
else
options = { ...lastContext }
}
@@ -102,15 +127,18 @@ async function chatReplyProcess(
async function fetchBalance() {
const OPENAI_API_KEY = process.env.OPENAI_API_KEY
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL
if (!isNotEmptyString(OPENAI_API_KEY))
return Promise.resolve('-')
const API_BASE_URL = isNotEmptyString(OPENAI_API_BASE_URL)
? OPENAI_API_BASE_URL
: 'https://api.openai.com'
try {
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`,
}
const response = await axios.get('https://api.openai.com/dashboard/billing/credit_grants', { headers })
const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${OPENAI_API_KEY}` }
const response = await axios.get(`${API_BASE_URL}/dashboard/billing/credit_grants`, { headers })
const balance = response.data.total_available ?? 0
return Promise.resolve(balance.toFixed(3))
}
@@ -133,17 +161,19 @@ async function chatConfig() {
}
function setupProxy(options: ChatGPTAPIOptions | ChatGPTUnofficialProxyAPIOptions) {
if (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) {
if (isNotEmptyString(process.env.SOCKS_PROXY_HOST) && isNotEmptyString(process.env.SOCKS_PROXY_PORT)) {
const agent = new SocksProxyAgent({
hostname: process.env.SOCKS_PROXY_HOST,
port: process.env.SOCKS_PROXY_PORT,
userId: isNotEmptyString(process.env.SOCKS_PROXY_USERNAME) ? process.env.SOCKS_PROXY_USERNAME : undefined,
password: isNotEmptyString(process.env.SOCKS_PROXY_PASSWORD) ? process.env.SOCKS_PROXY_PASSWORD : undefined,
})
options.fetch = (url, options) => {
return fetch(url, { agent, ...options })
}
}
else {
if (process.env.HTTPS_PROXY || process.env.ALL_PROXY) {
if (isNotEmptyString(process.env.HTTPS_PROXY) || isNotEmptyString(process.env.ALL_PROXY)) {
const httpsProxy = process.env.HTTPS_PROXY || process.env.ALL_PROXY
if (httpsProxy) {
const agent = new HttpsProxyAgent(httpsProxy)

View File

@@ -0,0 +1,8 @@
import type { ChatMessage } from 'chatgpt'
export interface RequestOptions {
message: string
lastContext?: { conversationId?: string; parentMessageId?: string }
process?: (chat: ChatMessage) => void
systemMessage?: string
}

View File

@@ -1,7 +1,9 @@
import express from 'express'
import type { ChatContext, ChatMessage } from './chatgpt'
import type { RequestProps } from './types'
import type { ChatMessage } from './chatgpt'
import { chatConfig, chatReplyProcess, currentModel } from './chatgpt'
import { auth } from './middleware/auth'
import { limiter } from './middleware/limiter'
import { isNotEmptyString } from './utils/is'
const app = express()
@@ -17,15 +19,20 @@ app.all('*', (_, res, next) => {
next()
})
router.post('/chat-process', auth, async (req, res) => {
router.post('/chat-process', [auth, limiter], async (req, res) => {
res.setHeader('Content-type', 'application/octet-stream')
try {
const { prompt, options = {} } = req.body as { prompt: string; options?: ChatContext }
const { prompt, options = {}, systemMessage } = req.body as RequestProps
let firstChunk = true
await chatReplyProcess(prompt, options, (chat: ChatMessage) => {
res.write(firstChunk ? JSON.stringify(chat) : `\n${JSON.stringify(chat)}`)
firstChunk = false
await chatReplyProcess({
message: prompt,
lastContext: options,
process: (chat: ChatMessage) => {
res.write(firstChunk ? JSON.stringify(chat) : `\n${JSON.stringify(chat)}`)
firstChunk = false
},
systemMessage,
})
}
catch (error) {
@@ -36,7 +43,7 @@ router.post('/chat-process', auth, async (req, res) => {
}
})
router.post('/config', async (req, res) => {
router.post('/config', auth, async (req, res) => {
try {
const response = await chatConfig()
res.send(response)
@@ -75,5 +82,6 @@ router.post('/verify', async (req, res) => {
app.use('', router)
app.use('/api', router)
app.set('trust proxy', 1)
app.listen(3002, () => globalThis.console.log('Server is running on port 3002'))

View File

@@ -0,0 +1,19 @@
import { rateLimit } from 'express-rate-limit'
import { isNotEmptyString } from '../utils/is'
const MAX_REQUEST_PER_HOUR = process.env.MAX_REQUEST_PER_HOUR
const maxCount = (isNotEmptyString(MAX_REQUEST_PER_HOUR) && !isNaN(Number(MAX_REQUEST_PER_HOUR)))
? parseInt(MAX_REQUEST_PER_HOUR)
: 0 // 0 means unlimited
const limiter = rateLimit({
windowMs: 60 * 60 * 1000, // Maximum number of accesses within an hour
max: maxCount,
statusCode: 200, // 200 means successbut the message is 'Too many request from this IP in 1 hour'
message: async (req, res) => {
res.send({ status: 'Fail', message: 'Too many request from this IP in 1 hour', data: null })
},
})
export { limiter }

View File

@@ -1,5 +1,11 @@
import type { FetchFn } from 'chatgpt'
export interface RequestProps {
prompt: string
options?: ChatContext
systemMessage: string
}
export interface ChatContext {
conversationId?: string
parentMessageId?: string

View File

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

View File

@@ -1,5 +1,6 @@
import type { AxiosProgressEvent, GenericAbortSignal } from 'axios'
import { post } from '@/utils/request'
import { useSettingStore } from '@/store'
export function fetchChatAPI<T = any>(
prompt: string,
@@ -26,9 +27,11 @@ export function fetchChatAPIProcess<T = any>(
signal?: GenericAbortSignal
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void },
) {
const settingStore = useSettingStore()
return post<T>({
url: '/chat-process',
data: { prompt: params.prompt, options: params.options },
data: { prompt: params.prompt, options: params.options, systemMessage: settingStore.systemMessage },
signal: params.signal,
onDownloadProgress: params.onDownloadProgress,
})

View File

@@ -1,14 +1,14 @@
[
{
"key": "chatgpt-prompt-collection",
"desc": "Nothing1024收集整理的prompts",
"downloadUrl": "https://raw.githubusercontent.com/Nothing1024/chatgpt-prompt-collection/main/awesome-chatgpt-prompts-zh.json",
"url": "https://github.com/Nothing1024/chatgpt-prompt-collection"
},
{
"key": "awesome-chatgpt-prompts-zh",
"desc": "ChatGPT 中文调教指南",
"downloadUrl": "https://raw.githubusercontent.com/PlexPt/awesome-chatgpt-prompts-zh/main/prompts-zh.json",
"url": "https://github.com/PlexPt/awesome-chatgpt-prompts-zh"
},
{
"key": "awesome-chatgpt-prompts-zh-TW",
"desc": "ChatGPT 中文調教指南 (透過 OpenAI / OpenCC 協助,從簡體中文轉換為繁體中文的版本)",
"downloadUrl": "https://raw.githubusercontent.com/PlexPt/awesome-chatgpt-prompts-zh/main/prompts-zh-TW.json",
"url": "https://github.com/PlexPt/awesome-chatgpt-prompts-zh"
}
]

View File

@@ -1,7 +1,7 @@
<script setup lang='ts'>
import type { DataTableColumns } from 'naive-ui'
import { computed, h, ref, watch } from 'vue'
import { NButton, NCard, NDataTable, NDivider, NInput, NLayoutContent, NList, NListItem, NModal, NPopconfirm, NSpace, NTabPane, NTabs, NThing, useMessage } from 'naive-ui'
import { NButton, NCard, NDataTable, NDivider, NInput, NList, NListItem, NModal, NPopconfirm, NSpace, NTabPane, NTabs, NThing, useMessage } from 'naive-ui'
import PromptRecommend from '../../../assets/recommend.json'
import { SvgIcon } from '..'
import { usePromptStore } from '@/store'
@@ -147,7 +147,7 @@ const clearPromptTemplate = () => {
message.success(t('common.clearSuccess'))
}
const importPromptTemplate = () => {
const importPromptTemplate = (from = 'online') => {
try {
const jsonData = JSON.parse(tempPromptValue.value)
let key = ''
@@ -168,7 +168,7 @@ const importPromptTemplate = () => {
}
for (const i of jsonData) {
if (!('key' in i) || !('value' in i))
if (!(key in i) || !(value in i))
throw new Error(t('store.importError'))
let safe = true
for (const j of promptList.value) {
@@ -191,6 +191,8 @@ const importPromptTemplate = () => {
catch {
message.error('JSON 格式错误,请检查 JSON 格式')
}
if (from === 'local')
showModal.value = !showModal.value
}
// 模板导出
@@ -408,17 +410,12 @@ const dataSource = computed(() => {
</NButton>
</div>
<NDivider />
<NLayoutContent
style="height: 360px"
content-style="background: none;"
:native-scrollbar="false"
>
<div class="max-h-[360px] overflow-y-auto space-y-4">
<NCard
v-for="info in promptRecommendList"
:key="info.key" :title="info.key"
style="margin: 5px;"
embedded
:bordered="true"
embedded
>
<p
class="overflow-hidden text-ellipsis whitespace-nowrap"
@@ -442,7 +439,7 @@ const dataSource = computed(() => {
</div>
</template>
</NCard>
</NLayoutContent>
</div>
</NTabPane>
</NTabs>
</div>
@@ -474,7 +471,7 @@ const dataSource = computed(() => {
block
type="primary"
:disabled="inputStatus"
@click="() => { importPromptTemplate() }"
@click="() => { importPromptTemplate('local') }"
>
{{ t('common.import') }}
</NButton>

View File

@@ -0,0 +1,46 @@
<script lang="ts" setup>
import { ref } from 'vue'
import { NButton, NInput, useMessage } from 'naive-ui'
import { useSettingStore } from '@/store'
import type { SettingsState } from '@/store/modules/settings/helper'
import { t } from '@/locales'
const settingStore = useSettingStore()
const ms = useMessage()
const systemMessage = ref(settingStore.systemMessage ?? '')
function updateSettings(options: Partial<SettingsState>) {
settingStore.updateSetting(options)
ms.success(t('common.success'))
}
function handleReset() {
settingStore.resetSetting()
ms.success(t('common.success'))
window.location.reload()
}
</script>
<template>
<div class="p-4 space-y-5 min-h-[200px]">
<div class="space-y-6">
<div class="flex items-center space-x-4">
<span class="flex-shrink-0 w-[100px]">{{ $t('setting.role') }}</span>
<div class="flex-1">
<NInput v-model:value="systemMessage" type="textarea" :autosize="{ minRows: 1, maxRows: 4 }" />
</div>
<NButton size="tiny" text type="primary" @click="updateSettings({ systemMessage })">
{{ $t('common.save') }}
</NButton>
</div>
<div class="flex items-center space-x-4">
<span class="flex-shrink-0 w-[100px]">&nbsp;</span>
<NButton size="small" @click="handleReset">
{{ $t('common.reset') }}
</NButton>
</div>
</div>
</div>
</template>

View File

@@ -150,7 +150,6 @@ function handleImportButtonClick(): void {
{{ $t('common.save') }}
</NButton>
</div>
<div
class="flex items-center space-x-4"
:class="isMobile && 'items-start'"

View File

@@ -2,13 +2,11 @@
import { computed, ref } from 'vue'
import { NModal, NTabPane, NTabs } from 'naive-ui'
import General from './General.vue'
import Advanced from './Advanced.vue'
import About from './About.vue'
import { useAuthStore } from '@/store'
import { SvgIcon } from '@/components/common'
const props = defineProps<Props>()
const emit = defineEmits<Emit>()
interface Props {
visible: boolean
}
@@ -17,6 +15,14 @@ interface Emit {
(e: 'update:visible', visible: boolean): void
}
const props = defineProps<Props>()
const emit = defineEmits<Emit>()
const authStore = useAuthStore()
const isChatGPTAPI = computed<boolean>(() => !!authStore.isChatGPTAPI)
const active = ref('General')
const show = computed({
@@ -42,6 +48,15 @@ const show = computed({
<General />
</div>
</NTabPane>
<NTabPane v-if="isChatGPTAPI" name="Advanced" tab="Advanced">
<template #tab>
<SvgIcon class="text-lg" icon="ri:equalizer-line" />
<span class="ml-2">{{ $t('setting.advanced') }}</span>
</template>
<div class="min-h-[100px]">
<Advanced />
</div>
</NTabPane>
<NTabPane name="Config" tab="Config">
<template #tab>
<SvgIcon class="text-lg" icon="ri:list-settings-line" />

View File

@@ -28,6 +28,7 @@ export default {
unauthorizedTips: 'Unauthorized, please verify first.',
},
chat: {
newChatButton: 'New Chat',
placeholder: 'Ask me anything...(Shift + Enter = line break)',
placeholderMobile: 'Ask me anything...',
copy: 'Copy',
@@ -46,14 +47,18 @@ export default {
deleteMessageConfirm: 'Are you sure to delete this message?',
deleteHistoryConfirm: 'Are you sure to clear this history?',
clearHistoryConfirm: 'Are you sure to clear chat history?',
preview: 'Preview',
showRawText: 'Show as raw text',
},
setting: {
setting: 'Setting',
general: 'General',
advanced: 'Advanced',
config: 'Config',
avatarLink: 'Avatar Link',
name: 'Name',
description: 'Description',
role: 'Role',
resetUserInfo: 'Reset UserInfo',
chatHistory: 'ChatHistory',
theme: 'Theme',
@@ -66,6 +71,7 @@ export default {
balance: 'API Balance',
},
store: {
siderButton: 'Prompt Store',
local: 'Local',
online: 'Online',
title: 'Title',

View File

@@ -28,6 +28,7 @@ export default {
unauthorizedTips: '未经授权,请先进行验证。',
},
chat: {
newChatButton: '新建聊天',
placeholder: '来说点什么吧...Shift + Enter = 换行)',
placeholderMobile: '来说点什么...',
copy: '复制',
@@ -46,14 +47,18 @@ export default {
deleteMessageConfirm: '是否删除此消息?',
deleteHistoryConfirm: '确定删除此记录?',
clearHistoryConfirm: '确定清空聊天记录?',
preview: '预览',
showRawText: '显示原文',
},
setting: {
setting: '设置',
general: '总览',
advanced: '高级',
config: '配置',
avatarLink: '头像链接',
name: '名称',
description: '描述',
role: '角色设定',
resetUserInfo: '重置用户信息',
chatHistory: '聊天记录',
theme: '主题',
@@ -66,6 +71,7 @@ export default {
balance: 'API余额',
},
store: {
siderButton: '提示词商店',
local: '本地',
online: '在线',
title: '标题',

View File

@@ -28,6 +28,7 @@ export default {
unauthorizedTips: '未經授權,請先進行驗證。',
},
chat: {
newChatButton: '新建對話',
placeholder: '來說點什麼...Shift + Enter = 換行)',
placeholderMobile: '來說點什麼...',
copy: '複製',
@@ -46,14 +47,18 @@ export default {
deleteMessageConfirm: '是否刪除此訊息?',
deleteHistoryConfirm: '確定刪除此紀錄?',
clearHistoryConfirm: '確定清除紀錄?',
preview: '預覽',
showRawText: '顯示原文',
},
setting: {
setting: '設定',
general: '總覽',
advanced: '高級',
config: '設定',
avatarLink: '頭貼連結',
name: '名稱',
description: '描述',
role: '角色設定',
resetUserInfo: '重設使用者資訊',
chatHistory: '紀錄',
theme: '主題',
@@ -66,6 +71,7 @@ export default {
balance: 'API余額',
},
store: {
siderButton: '提示詞商店',
local: '本機',
online: '線上',
title: '標題',

View File

@@ -9,7 +9,10 @@ export function setupPageGuard(router: Router) {
const data = await authStore.getSession()
if (String(data.auth) === 'false' && authStore.token)
authStore.removeToken()
next()
if (to.path === '/500')
next({ name: 'Root' })
else
next()
}
catch (error) {
if (to.path !== '/500')

View File

@@ -14,7 +14,7 @@ export function defaultState(): Chat.ChatState {
export function getLocalState(): Chat.ChatState {
const localState = ss.get(LOCAL_NAME)
return localState ?? defaultState()
return { ...defaultState(), ...localState }
}
export function setLocalState(state: Chat.ChatState) {

View File

@@ -2,4 +2,5 @@ export * from './app'
export * from './chat'
export * from './user'
export * from './prompt'
export * from './settings'
export * from './auth'

View File

@@ -0,0 +1,26 @@
import { ss } from '@/utils/storage'
const LOCAL_NAME = 'settingsStorage'
export interface SettingsState {
systemMessage: string
}
export function defaultSetting(): SettingsState {
return {
systemMessage: 'You are ChatGPT, a large language model trained by OpenAI. Follow the user\'s instructions carefully. Respond using markdown.',
}
}
export function getLocalState(): SettingsState {
const localSetting: SettingsState | undefined = ss.get(LOCAL_NAME)
return { ...defaultSetting(), ...localSetting }
}
export function setLocalState(setting: SettingsState): void {
ss.set(LOCAL_NAME, setting)
}
export function removeLocalState() {
ss.remove(LOCAL_NAME)
}

View File

@@ -0,0 +1,22 @@
import { defineStore } from 'pinia'
import type { SettingsState } from './helper'
import { defaultSetting, getLocalState, removeLocalState, setLocalState } from './helper'
export const useSettingStore = defineStore('setting-store', {
state: (): SettingsState => getLocalState(),
actions: {
updateSetting(settings: Partial<SettingsState>) {
this.$state = { ...this.$state, ...settings }
this.recordState()
},
resetSetting() {
this.$state = defaultSetting()
removeLocalState()
},
recordState() {
setLocalState(this.$state)
},
},
})

View File

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

View File

@@ -2,6 +2,7 @@
interface ImportMetaEnv {
readonly VITE_GLOB_API_URL: string;
readonly VITE_GLOB_API_TIMEOUT: string;
readonly VITE_APP_API_BASE_URL: string;
readonly VITE_GLOB_OPEN_LONG_REPLY: string;
readonly VITE_GLOB_APP_PWA: string;
}

View File

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

View File

@@ -2,6 +2,7 @@
import { computed, ref } from 'vue'
import MarkdownIt from 'markdown-it'
import mdKatex from '@traptitech/markdown-it-katex'
import mila from 'markdown-it-link-attributes'
import hljs from 'highlight.js'
import { useBasicLayout } from '@/hooks/useBasicLayout'
import { t } from '@/locales'
@@ -11,6 +12,7 @@ interface Props {
error?: boolean
text?: string
loading?: boolean
asRawText?: boolean
}
const props = defineProps<Props>()
@@ -31,6 +33,7 @@ const mdi = new MarkdownIt({
},
})
mdi.use(mila, { attrs: { target: '_blank', rel: 'noopener' } })
mdi.use(mdKatex, { blockClass: 'katexmath-block rounded-md p-[10px]', errorColor: ' #cc0000' })
const wrapClass = computed(() => {
@@ -41,13 +44,14 @@ const wrapClass = computed(() => {
isMobile.value ? 'p-2' : 'px-3 py-2',
props.inversion ? 'bg-[#d2f9d1]' : 'bg-[#f4f6f8]',
props.inversion ? 'dark:bg-[#a1dc95]' : 'dark:bg-[#1e1e20]',
props.inversion ? 'message-request' : 'message-reply',
{ 'text-red-500': props.error },
]
})
const text = computed(() => {
const value = props.text ?? ''
if (!props.inversion)
if (!props.asRawText)
return mdi.render(value)
return value
})
@@ -61,15 +65,14 @@ defineExpose({ textRef })
<template>
<div class="text-black" :class="wrapClass">
<template v-if="loading">
<span class="dark:text-white w-[4px] h-[20px] block animate-blink" />
</template>
<template v-else>
<div ref="textRef" class="leading-relaxed break-words">
<div v-if="!inversion" class="markdown-body" v-html="text" />
<div v-else class="whitespace-pre-wrap" v-text="text" />
<div ref="textRef" class="leading-relaxed break-words">
<div v-if="!inversion" class="flex items-end">
<div v-if="!asRawText" class="w-full markdown-body" v-html="text" />
<div v-else class="w-full whitespace-pre-wrap" v-text="text" />
<span v-if="loading" class="dark:text-white w-[4px] h-[20px] block animate-blink" />
</div>
</template>
<div v-else class="whitespace-pre-wrap" v-text="text" />
</div>
</div>
</template>

View File

@@ -1,5 +1,5 @@
<script setup lang='ts'>
import { ref } from 'vue'
import { computed, ref } from 'vue'
import { NDropdown } from 'naive-ui'
import AvatarComponent from './Avatar.vue'
import TextComponent from './Text.vue'
@@ -7,6 +7,7 @@ import { SvgIcon } from '@/components/common'
import { copyText } from '@/utils/format'
import { useIconRender } from '@/hooks/useIconRender'
import { t } from '@/locales'
import { useBasicLayout } from '@/hooks/useBasicLayout'
interface Props {
dateTime?: string
@@ -25,40 +26,66 @@ const props = defineProps<Props>()
const emit = defineEmits<Emit>()
const { isMobile } = useBasicLayout()
const { iconRender } = useIconRender()
const textRef = ref<HTMLElement>()
const options = [
{
label: t('chat.copy'),
key: 'copyText',
icon: iconRender({ icon: 'ri:file-copy-2-line' }),
},
{
label: t('common.delete'),
key: 'delete',
icon: iconRender({ icon: 'ri:delete-bin-line' }),
},
]
const asRawText = ref(props.inversion)
function handleSelect(key: 'copyRaw' | 'copyText' | 'delete') {
const messageRef = ref<HTMLElement>()
const options = computed(() => {
const common = [
{
label: t('chat.copy'),
key: 'copyText',
icon: iconRender({ icon: 'ri:file-copy-2-line' }),
},
{
label: t('common.delete'),
key: 'delete',
icon: iconRender({ icon: 'ri:delete-bin-line' }),
},
]
if (!props.inversion) {
common.unshift({
label: asRawText.value ? t('chat.preview') : t('chat.showRawText'),
key: 'toggleRenderType',
icon: iconRender({ icon: asRawText.value ? 'ic:outline-code-off' : 'ic:outline-code' }),
})
}
return common
})
function handleSelect(key: 'copyText' | 'delete' | 'toggleRenderType') {
switch (key) {
case 'copyText':
copyText({ text: props.text ?? '' })
return
case 'toggleRenderType':
asRawText.value = !asRawText.value
return
case 'delete':
emit('delete')
}
}
function handleRegenerate() {
messageRef.value?.scrollIntoView()
emit('regenerate')
}
</script>
<template>
<div class="flex w-full mb-6 overflow-hidden" :class="[{ 'flex-row-reverse': inversion }]">
<div
ref="messageRef"
class="flex w-full mb-6 overflow-hidden"
:class="[{ 'flex-row-reverse': inversion }]"
>
<div
class="flex items-center justify-center flex-shrink-0 h-8 overflow-hidden rounded-full basis-8"
:class="[inversion ? 'ml-2' : 'mr-2']"
@@ -79,6 +106,7 @@ function handleRegenerate() {
:error="error"
:text="text"
:loading="loading"
:as-raw-text="asRawText"
/>
<div class="flex flex-col">
<button
@@ -88,7 +116,12 @@ function handleRegenerate() {
>
<SvgIcon icon="ri:restart-line" />
</button>
<NDropdown :placement="!inversion ? 'right' : 'left'" :options="options" @select="handleSelect">
<NDropdown
:trigger="isMobile ? 'click' : 'hover'"
:placement="!inversion ? 'right' : 'left'"
:options="options"
@select="handleSelect"
>
<button class="transition text-neutral-300 hover:text-neutral-800 dark:hover:text-neutral-200">
<SvgIcon icon="ri:more-2-fill" />
</button>

View File

@@ -45,20 +45,29 @@
align-items: center;
color: #b3b3b3;
&__copy{
&__copy {
cursor: pointer;
margin-left: 0.5rem;
user-select: none;
&:hover {
color: #65a665;
}
}
}
}
}
html.dark {
.message-reply {
.whitespace-pre-wrap {
white-space: pre-wrap;
color: var(--n-text-color);
}
}
.highlight pre,
pre {
background-color: #282c34;

View File

@@ -28,7 +28,7 @@ export function useScroll(): ScrollReturn {
const scrollToBottomIfAtBottom = async () => {
await nextTick()
if (scrollRef.value) {
const threshold = 50 // 阈值,表示滚动条到底部的距离阈值
const threshold = 100 // 阈值,表示滚动条到底部的距离阈值
const distanceToBottom = scrollRef.value.scrollHeight - scrollRef.value.scrollTop - scrollRef.value.clientHeight
if (distanceToBottom <= threshold)
scrollRef.value.scrollTop = scrollRef.value.scrollHeight

View File

@@ -1,4 +1,5 @@
<script setup lang='ts'>
import type { Ref } from 'vue'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { storeToRefs } from 'pinia'
@@ -30,7 +31,7 @@ useCopyCode()
const { isMobile } = useBasicLayout()
const { addChat, updateChat, updateChatSome, getChatByUuidAndIndex } = useChat()
const { scrollRef, scrollToBottom } = useScroll()
const { scrollRef, scrollToBottom, scrollToBottomIfAtBottom } = useScroll()
const { usingContext, toggleUsingContext } = useUsingContext()
const { uuid } = route.params as { uuid: string }
@@ -40,12 +41,20 @@ const conversationList = computed(() => dataSources.value.filter(item => (!item.
const prompt = ref<string>('')
const loading = ref<boolean>(false)
const inputRef = ref<Ref | null>(null)
// 添加PromptStore
const promptStore = usePromptStore()
// 使用storeToRefs保证store修改后联想部分能够重新渲染
const { promptList: promptTemplate } = storeToRefs<any>(promptStore)
// 未知原因刷新页面loading 状态不会重置,手动重置
dataSources.value.forEach((item, index) => {
if (item.loading)
updateChatSome(+uuid, index, { loading: false })
})
function handleSubmit() {
onConversation()
}
@@ -108,7 +117,7 @@ async function onConversation() {
const xhr = event.target
const { responseText } = xhr
// Always process the final line
const lastIndex = responseText.lastIndexOf('\n')
const lastIndex = responseText.lastIndexOf('\n', responseText.length - 2)
let chunk = responseText
if (lastIndex !== -1)
chunk = responseText.substring(lastIndex)
@@ -119,10 +128,10 @@ async function onConversation() {
dataSources.value.length - 1,
{
dateTime: new Date().toLocaleString(),
text: lastText + data.text ?? '',
text: lastText + (data.text ?? ''),
inversion: false,
error: false,
loading: false,
loading: true,
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
requestOptions: { prompt: message, options: { ...options } },
},
@@ -135,13 +144,14 @@ async function onConversation() {
return fetchChatAPIOnce()
}
scrollToBottom()
scrollToBottomIfAtBottom()
}
catch (error) {
//
//
}
},
})
updateChatSome(+uuid, dataSources.value.length - 1, { loading: false })
}
await fetchChatAPIOnce()
@@ -157,7 +167,7 @@ async function onConversation() {
loading: false,
},
)
scrollToBottom()
scrollToBottomIfAtBottom()
return
}
@@ -189,7 +199,7 @@ async function onConversation() {
requestOptions: { prompt: message, options: { ...options } },
},
)
scrollToBottom()
scrollToBottomIfAtBottom()
}
finally {
loading.value = false
@@ -238,7 +248,7 @@ async function onRegenerate(index: number) {
const xhr = event.target
const { responseText } = xhr
// Always process the final line
const lastIndex = responseText.lastIndexOf('\n')
const lastIndex = responseText.lastIndexOf('\n', responseText.length - 2)
let chunk = responseText
if (lastIndex !== -1)
chunk = responseText.substring(lastIndex)
@@ -249,10 +259,10 @@ async function onRegenerate(index: number) {
index,
{
dateTime: new Date().toLocaleString(),
text: lastText + data.text ?? '',
text: lastText + (data.text ?? ''),
inversion: false,
error: false,
loading: false,
loading: true,
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
requestOptions: { prompt: message, ...options },
},
@@ -270,6 +280,7 @@ async function onRegenerate(index: number) {
}
},
})
updateChatSome(+uuid, index, { loading: false })
}
await fetchChatAPIOnce()
}
@@ -445,6 +456,8 @@ const footerClass = computed(() => {
onMounted(() => {
scrollToBottom()
if (inputRef.value && !isMobile.value)
inputRef.value?.focus()
})
onUnmounted(() => {
@@ -462,11 +475,7 @@ onUnmounted(() => {
@toggle-using-context="toggleUsingContext"
/>
<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
id="image-wrapper"
class="w-full max-w-screen-xl m-auto dark:bg-[#101014]"
@@ -525,6 +534,7 @@ onUnmounted(() => {
<NAutoComplete v-model:value="prompt" :options="searchOptions" :render-label="renderOption">
<template #default="{ handleInput, handleBlur, handleFocus }">
<NInput
ref="inputRef"
v-model:value="prompt"
type="textarea"
:placeholder="placeholder"

View File

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

View File

@@ -18,6 +18,8 @@ const collapsed = computed(() => appStore.siderCollapsed)
function handleAdd() {
chatStore.addHistory({ title: 'New Chat', uuid: Date.now(), isEdit: false })
if (isMobile.value)
appStore.setSiderCollapsed(true)
}
function handleUpdateCollapsed() {
@@ -71,7 +73,7 @@ watch(
<main class="flex flex-col flex-1 min-h-0">
<div class="p-4">
<NButton dashed block @click="handleAdd">
New chat
{{ $t('chat.newChatButton') }}
</NButton>
</div>
<div class="flex-1 min-h-0 pb-4 overflow-hidden">
@@ -79,7 +81,7 @@ watch(
</div>
<div class="p-4">
<NButton block @click="show = true">
Prompt Store
{{ $t('store.siderButton') }}
</NButton>
</div>
</main>

9
start.cmd Normal file
View File

@@ -0,0 +1,9 @@
cd ./service
start pnpm start > service.log &
echo "Start service complete!"
cd ..
echo "" > front.log
start pnpm dev > front.log &
echo "Start front complete!"

View File

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