mirror of
https://github.com/Chanzhaoyu/chatgpt-web.git
synced 2025-07-30 18:48:31 +00:00
Compare commits
6 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
89712aada7 | ||
![]() |
3e9db49aad | ||
![]() |
2dcd292dd4 | ||
![]() |
90f6989445 | ||
![]() |
1406292405 | ||
![]() |
628187f5c3 |
22
CHANGELOG.md
22
CHANGELOG.md
@@ -1,3 +1,25 @@
|
||||
## v2.8.0
|
||||
|
||||
`2023-02-27`
|
||||
|
||||
- 感谢 [puppywang](https://github.com/Chanzhaoyu/chatgpt-web/commit/628187f5c3348bda0d0518f90699a86525d19018) 修复了 `2.7.0` 版本中关于流输出数据的问题(使用 `nginx` 需要自行配置 `octet-stream` 相关内容)
|
||||
|
||||
- 关于为什么使用 `octet-stream` 而不是 `sse`,是因为更好的兼容之前的模式。
|
||||
|
||||
- 建议更新到此版本获得比较完整的体验
|
||||
|
||||
### Enhancement
|
||||
- 优化了部份代码和类型提示
|
||||
- 输入框添加换行提示
|
||||
- 移动端输入框现在回车为换行,而不是直接提交
|
||||
- 移动端双击标题返回顶部,箭头返回底部
|
||||
|
||||
### BugFix
|
||||
- 流输出数据下的问题[#122]
|
||||
- 修复了 `API Key` 下部份代码不换行的问题
|
||||
- 修复移动端深色模式部份样式问题[#123][#126]
|
||||
- 修复主题模式图标不一致的问题[#126]
|
||||
|
||||
## v2.7.3
|
||||
|
||||
`2023-02-25`
|
||||
|
26
README.md
26
README.md
@@ -2,8 +2,8 @@
|
||||
|
||||
> 使用 `express` 和 `vue3` 搭建的支持 `ChatGPT` 双模型演示网页
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
- [ChatGPT Web](#chatgpt-web)
|
||||
- [介绍](#介绍)
|
||||
@@ -30,6 +30,7 @@
|
||||
- [前端网页](#前端网页-1)
|
||||
- [常见问题](#常见问题)
|
||||
- [参与贡献](#参与贡献)
|
||||
- [赞助](#赞助)
|
||||
- [License](#license)
|
||||
## 介绍
|
||||
|
||||
@@ -38,14 +39,14 @@
|
||||
| 方式 | 免费? | 可靠性 | 质量 |
|
||||
| ---- | ---- | ---- | ---- |
|
||||
| `ChatGPTAPI(GPT-3)` | 否 | 可靠 | 较笨 |
|
||||
| `ChatGPTUnofficialProxyAPI(网页 accessToken)` | 是 | 不可靠 | 聪明 |
|
||||
|
||||
***Note:*** 网页 `accessToken` 存在大约 8 小时,而且国内地区网络问题更推荐使用 `GPT-3` 的方式
|
||||
| `ChatGPTUnofficialProxyAPI(网页 accessToken)` | 是 | 相对不可靠 | 聪明 |
|
||||
|
||||
对比:
|
||||
1. `ChatGPTAPI` 使用 `text-davinci-003` 通过官方`OpenAI`补全`API`模拟`ChatGPT`(最稳健的方法,但它不是免费的,并且没有使用针对聊天进行微调的模型)
|
||||
2. `ChatGPTUnofficialProxyAPI` 使用非官方代理服务器访问 `ChatGPT` 的后端`API`,绕过`Cloudflare`(使用真实的的`ChatGPT`,非常轻量级,但依赖于第三方服务器,并且有速率限制)
|
||||
|
||||
[查看详情](https://github.com/Chanzhaoyu/chatgpt-web/issues/138)
|
||||
|
||||
切换方式:
|
||||
1. 进入 `service/.env` 文件
|
||||
2. 使用 `OpenAI API Key` 请填写 `OPENAI_API_KEY` 字段 [(获取 apiKey)](https://platform.openai.com/overview)
|
||||
@@ -257,5 +258,20 @@ A: `vscode` 请安装项目推荐插件,或手动安装 `Eslint` 插件。
|
||||
<img src="https://contrib.rocks/image?repo=Chanzhaoyu/chatgpt-web" />
|
||||
</a>
|
||||
|
||||
## 赞助
|
||||
|
||||
如果你觉得这个项目对你有帮助,并且情况允许的话,可以给我一点点支持,总之非常感谢支持~
|
||||
|
||||
<div style="display: flex; gap: 20px;">
|
||||
<div style="text-align: center">
|
||||
<img style="max-width: 100%" src="./docs/wechat.png" alt="微信" />
|
||||
<p>WeChat Pay</p>
|
||||
</div>
|
||||
<div style="text-align: center">
|
||||
<img style="max-width: 100%" src="./docs/alipay.png" alt="支付宝" />
|
||||
<p>Alipay</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
## License
|
||||
MIT © [ChenZhaoYu](./license)
|
||||
|
BIN
docs/alipay.png
Normal file
BIN
docs/alipay.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 61 KiB |
BIN
docs/c1-2.8.0.png
Normal file
BIN
docs/c1-2.8.0.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 123 KiB |
BIN
docs/c2-2.8.0.png
Normal file
BIN
docs/c2-2.8.0.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 396 KiB |
BIN
docs/wechat.png
Normal file
BIN
docs/wechat.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 80 KiB |
@@ -1,6 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-cmn-Hans">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
@@ -9,7 +8,7 @@
|
||||
<title>ChatGPT Web</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<body class="dark:bg-black">
|
||||
<div id="app">
|
||||
<style>
|
||||
.loading-wrap {
|
||||
|
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "chatgpt-web",
|
||||
"version": "2.7.3",
|
||||
"version": "2.8.0",
|
||||
"private": false,
|
||||
"description": "ChatGPT Web",
|
||||
"author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>",
|
||||
|
@@ -28,7 +28,9 @@
|
||||
"dotenv": "^16.0.3",
|
||||
"esno": "^0.16.3",
|
||||
"express": "^4.18.2",
|
||||
"isomorphic-fetch": "^3.0.0"
|
||||
"isomorphic-fetch": "^3.0.0",
|
||||
"node-fetch": "^3.3.0",
|
||||
"socks-proxy-agent": "^7.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^0.35.2",
|
||||
|
82
service/pnpm-lock.yaml
generated
82
service/pnpm-lock.yaml
generated
@@ -10,7 +10,9 @@ specifiers:
|
||||
esno: ^0.16.3
|
||||
express: ^4.18.2
|
||||
isomorphic-fetch: ^3.0.0
|
||||
node-fetch: ^3.3.0
|
||||
rimraf: ^4.1.2
|
||||
socks-proxy-agent: ^7.0.0
|
||||
tsup: ^6.6.3
|
||||
typescript: ^4.9.5
|
||||
|
||||
@@ -20,6 +22,8 @@ dependencies:
|
||||
esno: 0.16.3
|
||||
express: 4.18.2
|
||||
isomorphic-fetch: 3.0.0
|
||||
node-fetch: 3.3.0
|
||||
socks-proxy-agent: 7.0.0
|
||||
|
||||
devDependencies:
|
||||
'@antfu/eslint-config': 0.35.2_7kw3g6rralp5ps6mg3uyzz6azm
|
||||
@@ -641,6 +645,15 @@ packages:
|
||||
hasBin: true
|
||||
dev: true
|
||||
|
||||
/agent-base/6.0.2:
|
||||
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
|
||||
engines: {node: '>= 6.0.0'}
|
||||
dependencies:
|
||||
debug: 4.3.4
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
dev: false
|
||||
|
||||
/ajv-formats/2.1.1:
|
||||
resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==}
|
||||
peerDependenciesMeta:
|
||||
@@ -999,6 +1012,11 @@ packages:
|
||||
hasBin: true
|
||||
dev: true
|
||||
|
||||
/data-uri-to-buffer/4.0.1:
|
||||
resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}
|
||||
engines: {node: '>= 12'}
|
||||
dev: false
|
||||
|
||||
/debounce-fn/5.1.2:
|
||||
resolution: {integrity: sha512-Sr4SdOZ4vw6eQDvPYNxHogvrxmCIld/VenC5JbNrFwMiwd7lY/Z18ZFfo+EWNG4DD9nFlAujWAo/wGuOPHmy5A==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -1038,7 +1056,6 @@ packages:
|
||||
optional: true
|
||||
dependencies:
|
||||
ms: 2.1.2
|
||||
dev: true
|
||||
|
||||
/deep-is/0.1.4:
|
||||
resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}
|
||||
@@ -1748,6 +1765,14 @@ packages:
|
||||
reusify: 1.0.4
|
||||
dev: true
|
||||
|
||||
/fetch-blob/3.2.0:
|
||||
resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}
|
||||
engines: {node: ^12.20 || >= 14.13}
|
||||
dependencies:
|
||||
node-domexception: 1.0.0
|
||||
web-streams-polyfill: 3.2.1
|
||||
dev: false
|
||||
|
||||
/file-entry-cache/6.0.1:
|
||||
resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==}
|
||||
engines: {node: ^10.12.0 || >=12.0.0}
|
||||
@@ -1819,6 +1844,13 @@ packages:
|
||||
is-callable: 1.2.7
|
||||
dev: true
|
||||
|
||||
/formdata-polyfill/4.0.10:
|
||||
resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==}
|
||||
engines: {node: '>=12.20.0'}
|
||||
dependencies:
|
||||
fetch-blob: 3.2.0
|
||||
dev: false
|
||||
|
||||
/forwarded/0.2.0:
|
||||
resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==}
|
||||
engines: {node: '>= 0.6'}
|
||||
@@ -2086,6 +2118,10 @@ packages:
|
||||
side-channel: 1.0.4
|
||||
dev: true
|
||||
|
||||
/ip/2.0.0:
|
||||
resolution: {integrity: sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==}
|
||||
dev: false
|
||||
|
||||
/ipaddr.js/1.9.1:
|
||||
resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}
|
||||
engines: {node: '>= 0.10'}
|
||||
@@ -2509,7 +2545,6 @@ packages:
|
||||
|
||||
/ms/2.1.2:
|
||||
resolution: {integrity: sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==}
|
||||
dev: true
|
||||
|
||||
/ms/2.1.3:
|
||||
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||
@@ -2535,6 +2570,11 @@ packages:
|
||||
engines: {node: '>= 0.6'}
|
||||
dev: false
|
||||
|
||||
/node-domexception/1.0.0:
|
||||
resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}
|
||||
engines: {node: '>=10.5.0'}
|
||||
dev: false
|
||||
|
||||
/node-fetch/2.6.9:
|
||||
resolution: {integrity: sha512-DJm/CJkZkRjKKj4Zi4BsKVZh3ValV5IR5s7LVZnW+6YMh0W1BfNA8XSs6DLMGYlId5F3KnA70uu2qepcR08Qqg==}
|
||||
engines: {node: 4.x || >=6.0.0}
|
||||
@@ -2547,6 +2587,15 @@ packages:
|
||||
whatwg-url: 5.0.0
|
||||
dev: false
|
||||
|
||||
/node-fetch/3.3.0:
|
||||
resolution: {integrity: sha512-BKwRP/O0UvoMKp7GNdwPlObhYGB5DQqwhEDQlNKuoqwVYSxkSZCSbHjnFFmUEtwSKRPU4kNK8PbDYYitwaE3QA==}
|
||||
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
|
||||
dependencies:
|
||||
data-uri-to-buffer: 4.0.1
|
||||
fetch-blob: 3.2.0
|
||||
formdata-polyfill: 4.0.10
|
||||
dev: false
|
||||
|
||||
/normalize-package-data/2.5.0:
|
||||
resolution: {integrity: sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==}
|
||||
dependencies:
|
||||
@@ -3083,6 +3132,30 @@ packages:
|
||||
engines: {node: '>=8'}
|
||||
dev: true
|
||||
|
||||
/smart-buffer/4.2.0:
|
||||
resolution: {integrity: sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==}
|
||||
engines: {node: '>= 6.0.0', npm: '>= 3.0.0'}
|
||||
dev: false
|
||||
|
||||
/socks-proxy-agent/7.0.0:
|
||||
resolution: {integrity: sha512-Fgl0YPZ902wEsAyiQ+idGd1A7rSFx/ayC1CQVMw5P+EQx2V0SgpGtf6OKFhVjPflPUl9YMmEOnmfjCdMUsygww==}
|
||||
engines: {node: '>= 10'}
|
||||
dependencies:
|
||||
agent-base: 6.0.2
|
||||
debug: 4.3.4
|
||||
socks: 2.7.1
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
dev: false
|
||||
|
||||
/socks/2.7.1:
|
||||
resolution: {integrity: sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==}
|
||||
engines: {node: '>= 10.13.0', npm: '>= 3.0.0'}
|
||||
dependencies:
|
||||
ip: 2.0.0
|
||||
smart-buffer: 4.2.0
|
||||
dev: false
|
||||
|
||||
/source-map-support/0.5.21:
|
||||
resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==}
|
||||
dependencies:
|
||||
@@ -3440,6 +3513,11 @@ packages:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
||||
/web-streams-polyfill/3.2.1:
|
||||
resolution: {integrity: sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==}
|
||||
engines: {node: '>= 8'}
|
||||
dev: false
|
||||
|
||||
/webidl-conversions/3.0.1:
|
||||
resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
|
||||
dev: false
|
||||
|
@@ -1,20 +1,18 @@
|
||||
import * as dotenv from 'dotenv'
|
||||
import 'isomorphic-fetch'
|
||||
import type { ChatGPTAPI, ChatMessage, SendMessageOptions } from 'chatgpt'
|
||||
import { ChatGPTUnofficialProxyAPI } from 'chatgpt'
|
||||
import type { ChatMessage, SendMessageOptions } from 'chatgpt'
|
||||
import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt'
|
||||
import { SocksProxyAgent } from 'socks-proxy-agent'
|
||||
import fetch from 'node-fetch'
|
||||
import { sendResponse } from './utils'
|
||||
import type { ApiModel, ChatContext, ChatGPTAPIOptions, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from './types'
|
||||
|
||||
dotenv.config()
|
||||
|
||||
let apiModel: 'ChatGPTAPI' | 'ChatGPTUnofficialProxyAPI' | undefined
|
||||
|
||||
interface ChatContext {
|
||||
conversationId?: string
|
||||
parentMessageId?: string
|
||||
}
|
||||
|
||||
const timeoutMs: number = !isNaN(+process.env.TIMEOUT_MS) ? +process.env.TIMEOUT_MS : 30 * 1000
|
||||
|
||||
let apiModel: ApiModel
|
||||
|
||||
if (!process.env.OPENAI_API_KEY && !process.env.OPENAI_ACCESS_TOKEN)
|
||||
throw new Error('Missing OPENAI_API_KEY or OPENAI_ACCESS_TOKEN environment variable')
|
||||
|
||||
@@ -23,17 +21,34 @@ let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
|
||||
// To use ESM in CommonJS, you can use a dynamic import
|
||||
(async () => {
|
||||
// More Info: https://github.com/transitive-bullshit/chatgpt-api
|
||||
const { ChatGPTAPI } = await import('chatgpt')
|
||||
|
||||
if (process.env.OPENAI_API_KEY) {
|
||||
api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
|
||||
const options: ChatGPTAPIOptions = {
|
||||
apiKey: process.env.OPENAI_API_KEY,
|
||||
debug: false,
|
||||
}
|
||||
|
||||
api = new ChatGPTAPI({ ...options })
|
||||
apiModel = 'ChatGPTAPI'
|
||||
}
|
||||
else {
|
||||
let options = {}
|
||||
const options: ChatGPTUnofficialProxyAPIOptions = {
|
||||
accessToken: process.env.OPENAI_ACCESS_TOKEN,
|
||||
debug: false,
|
||||
}
|
||||
|
||||
if (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) {
|
||||
const agent = new SocksProxyAgent({
|
||||
hostname: process.env.SOCKS_PROXY_HOST,
|
||||
port: process.env.SOCKS_PROXY_PORT,
|
||||
})
|
||||
options.fetch = (url, options) => {
|
||||
return fetch(url, { agent, ...options })
|
||||
}
|
||||
}
|
||||
|
||||
if (process.env.API_REVERSE_PROXY)
|
||||
options = { apiReverseProxyUrl: process.env.API_REVERSE_PROXY }
|
||||
options.apiReverseProxyUrl = process.env.API_REVERSE_PROXY
|
||||
|
||||
api = new ChatGPTUnofficialProxyAPI({
|
||||
accessToken: process.env.OPENAI_ACCESS_TOKEN,
|
||||
@@ -65,6 +80,34 @@ async function chatReply(
|
||||
}
|
||||
}
|
||||
|
||||
async function chatReplyProcess(
|
||||
message: string,
|
||||
lastContext?: { conversationId?: string; parentMessageId?: string },
|
||||
process?: (chat: ChatMessage) => void,
|
||||
) {
|
||||
if (!message)
|
||||
return sendResponse({ type: 'Fail', message: 'Message is empty' })
|
||||
|
||||
try {
|
||||
let options: SendMessageOptions = { timeoutMs }
|
||||
|
||||
if (lastContext)
|
||||
options = { ...lastContext }
|
||||
|
||||
const response = await api.sendMessage(message, {
|
||||
...options,
|
||||
onProgress: (partialResponse) => {
|
||||
process?.(partialResponse)
|
||||
},
|
||||
})
|
||||
|
||||
return sendResponse({ type: 'Success', data: response })
|
||||
}
|
||||
catch (error: any) {
|
||||
return sendResponse({ type: 'Fail', message: error.message })
|
||||
}
|
||||
}
|
||||
|
||||
async function chatConfig() {
|
||||
return sendResponse({
|
||||
type: 'Success',
|
||||
@@ -72,10 +115,11 @@ async function chatConfig() {
|
||||
apiModel,
|
||||
reverseProxy: process.env.API_REVERSE_PROXY,
|
||||
timeoutMs,
|
||||
},
|
||||
socksProxy: (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT) ? (`${process.env.SOCKS_PROXY_HOST}:${process.env.SOCKS_PROXY_PORT}`) : '-',
|
||||
} as ModelConfig,
|
||||
})
|
||||
}
|
||||
|
||||
export type { ChatContext, ChatMessage }
|
||||
|
||||
export { chatReply, chatConfig }
|
||||
export { chatReply, chatReplyProcess, chatConfig }
|
||||
|
@@ -1,6 +1,6 @@
|
||||
import express from 'express'
|
||||
import type { ChatContext } from './chatgpt'
|
||||
import { chatConfig, chatReply } from './chatgpt'
|
||||
import type { ChatContext, ChatMessage } from './chatgpt'
|
||||
import { chatConfig, chatReply, chatReplyProcess } from './chatgpt'
|
||||
|
||||
const app = express()
|
||||
const router = express.Router()
|
||||
@@ -26,6 +26,25 @@ router.post('/chat', async (req, res) => {
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/chat-process', async (req, res) => {
|
||||
res.setHeader('Content-type', 'application/octet-stream')
|
||||
|
||||
try {
|
||||
const { prompt, options = {} } = req.body as { prompt: string; options?: ChatContext }
|
||||
let firstChunk = true
|
||||
await chatReplyProcess(prompt, options, (chat: ChatMessage) => {
|
||||
res.write(firstChunk ? JSON.stringify(chat) : `\n${JSON.stringify(chat)}`)
|
||||
firstChunk = false
|
||||
})
|
||||
}
|
||||
catch (error) {
|
||||
res.write(JSON.stringify(error))
|
||||
}
|
||||
finally {
|
||||
res.end()
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/config', async (req, res) => {
|
||||
try {
|
||||
const response = await chatConfig()
|
||||
|
30
service/src/types.ts
Normal file
30
service/src/types.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import type { FetchFn, openai } from 'chatgpt'
|
||||
|
||||
export interface ChatContext {
|
||||
conversationId?: string
|
||||
parentMessageId?: string
|
||||
}
|
||||
|
||||
export interface ChatGPTAPIOptions {
|
||||
apiKey: string
|
||||
debug?: boolean
|
||||
completionParams?: Partial<openai.CompletionParams>
|
||||
}
|
||||
|
||||
export interface ChatGPTUnofficialProxyAPIOptions {
|
||||
accessToken: string
|
||||
apiReverseProxyUrl?: string
|
||||
model?: string
|
||||
debug?: boolean
|
||||
headers?: Record<string, string>
|
||||
fetch?: FetchFn
|
||||
}
|
||||
|
||||
export interface ModelConfig {
|
||||
apiModel?: ApiModel
|
||||
reverseProxy?: string
|
||||
timeoutMs?: number
|
||||
socksProxy?: string
|
||||
}
|
||||
|
||||
export type ApiModel = 'ChatGPTAPI' | 'ChatGPTUnofficialProxyAPI' | undefined
|
@@ -1,4 +1,4 @@
|
||||
import type { GenericAbortSignal } from 'axios'
|
||||
import type { AxiosProgressEvent, GenericAbortSignal } from 'axios'
|
||||
import { post } from '@/utils/request'
|
||||
|
||||
export function fetchChatAPI<T = any>(
|
||||
@@ -18,3 +18,18 @@ export function fetchChatConfig<T = any>() {
|
||||
url: '/config',
|
||||
})
|
||||
}
|
||||
|
||||
export function fetchChatAPIProcess<T = any>(
|
||||
params: {
|
||||
prompt: string
|
||||
options?: { conversationId?: string; parentMessageId?: string }
|
||||
signal?: GenericAbortSignal
|
||||
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void },
|
||||
) {
|
||||
return post<T>({
|
||||
url: '/chat-process',
|
||||
data: { prompt: params.prompt, options: params.options },
|
||||
signal: params.signal,
|
||||
onDownloadProgress: params.onDownloadProgress,
|
||||
})
|
||||
}
|
||||
|
@@ -16,6 +16,7 @@ interface ConfigState {
|
||||
timeoutMs?: number
|
||||
reverseProxy?: string
|
||||
apiModel?: string
|
||||
socksProxy?: string
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
@@ -69,6 +70,7 @@ watch(
|
||||
<p>API方式:{{ config?.apiModel ?? '-' }}</p>
|
||||
<p>反向代理:{{ config?.reverseProxy ?? '-' }}</p>
|
||||
<p>超时时间:{{ config?.timeoutMs ?? '-' }}</p>
|
||||
<p>Socks代理:{{ config?.socksProxy ?? '-' }}</p>
|
||||
</div>
|
||||
</NCard>
|
||||
</NModal>
|
||||
|
@@ -6,6 +6,13 @@ export const useChatStore = defineStore('chat-store', {
|
||||
state: (): Chat.ChatState => getLocalState(),
|
||||
|
||||
getters: {
|
||||
getChatHistoryByCurrentActive(state: Chat.ChatState) {
|
||||
const index = state.history.findIndex(item => item.uuid === state.active)
|
||||
if (index !== -1)
|
||||
return state.history[index]
|
||||
return null
|
||||
},
|
||||
|
||||
getChatByUuid(state: Chat.ChatState) {
|
||||
return (uuid?: number) => {
|
||||
if (uuid)
|
||||
@@ -68,6 +75,18 @@ export const useChatStore = defineStore('chat-store', {
|
||||
return await this.reloadRoute(uuid)
|
||||
},
|
||||
|
||||
getChatByUuidAndIndex(uuid: number, index: number) {
|
||||
if (!uuid || uuid === 0) {
|
||||
if (this.chat.length)
|
||||
return this.chat[0].data[index]
|
||||
return null
|
||||
}
|
||||
const chatIndex = this.chat.findIndex(item => item.uuid === uuid)
|
||||
if (chatIndex !== -1)
|
||||
return this.chat[chatIndex].data[index]
|
||||
return null
|
||||
},
|
||||
|
||||
addChatByUuid(uuid: number, chat: Chat.Chat) {
|
||||
if (!uuid || uuid === 0) {
|
||||
if (this.history.length === 0) {
|
||||
|
@@ -2,15 +2,7 @@
|
||||
import { computed } from 'vue'
|
||||
import { marked } from 'marked'
|
||||
import hljs from 'highlight.js'
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
marked.setOptions({
|
||||
renderer: new marked.Renderer(),
|
||||
highlight(code) {
|
||||
return hljs.highlightAuto(code).value
|
||||
},
|
||||
})
|
||||
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||
|
||||
interface Props {
|
||||
inversion?: boolean
|
||||
@@ -19,12 +11,23 @@ interface Props {
|
||||
loading?: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const { isMobile } = useBasicLayout()
|
||||
|
||||
marked.setOptions({
|
||||
renderer: new marked.Renderer(),
|
||||
highlight(code) {
|
||||
return hljs.highlightAuto(code).value
|
||||
},
|
||||
})
|
||||
|
||||
const wrapClass = computed(() => {
|
||||
return [
|
||||
'text-wrap',
|
||||
'p-3',
|
||||
'min-w-[20px]',
|
||||
'rounded-md',
|
||||
isMobile.value ? 'p-2' : 'p-3',
|
||||
props.inversion ? 'bg-[#d2f9d1]' : 'bg-[#f4f6f8]',
|
||||
props.inversion ? 'dark:bg-[#a1dc95]' : 'dark:bg-[#1e1e20]',
|
||||
{ 'text-red-500': props.error },
|
||||
@@ -45,8 +48,8 @@ const text = computed(() => {
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="leading-relaxed break-all">
|
||||
<div v-if="!inversion" class="markdown-body" v-html="text" />
|
||||
<div v-else v-text="text" />
|
||||
<pre v-if="!inversion" class="markdown-body" v-html="text" />
|
||||
<div v-else class="whitespace-pre-wrap" v-text="text" />
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
@@ -13,7 +13,6 @@ interface Props {
|
||||
|
||||
interface Emit {
|
||||
(ev: 'regenerate'): void
|
||||
(ev: 'copy'): void
|
||||
(ev: 'delete'): void
|
||||
}
|
||||
|
||||
@@ -33,15 +32,15 @@ function handleRegenerate() {
|
||||
<template>
|
||||
<div class="flex w-full mb-6 overflow-hidden" :class="[{ 'flex-row-reverse': inversion }]">
|
||||
<div
|
||||
class="flex items-center justify-center rounded-full overflow-hidden flex-shrink-0 w-[32px] h-[32px]"
|
||||
:class="[inversion ? 'ml-3' : 'mr-3']"
|
||||
class="flex items-center justify-center flex-shrink-0 h-8 overflow-hidden rounded-full basis-8"
|
||||
:class="[inversion ? 'ml-2' : 'mr-2']"
|
||||
>
|
||||
<AvatarComponent :image="inversion" />
|
||||
</div>
|
||||
<div class="flex flex-col flex-1 text-sm" :class="[inversion ? 'items-end' : 'items-start']">
|
||||
<span class="text-xs text-[#b4bbc4]">
|
||||
<div class="overflow-hidden text-sm " :class="[inversion ? 'items-end' : 'items-start']">
|
||||
<p class="text-xs text-[#b4bbc4]" :class="[inversion ? 'text-right' : 'text-left']">
|
||||
{{ dateTime }}
|
||||
</span>
|
||||
</p>
|
||||
<div
|
||||
class="flex items-end gap-2 mt-2"
|
||||
:class="[inversion ? 'flex-row-reverse' : 'flex-row']"
|
||||
|
@@ -2,6 +2,10 @@
|
||||
background-color: transparent;
|
||||
font-size: 14px;
|
||||
|
||||
p{
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
ol {
|
||||
list-style-type: decimal;
|
||||
}
|
||||
|
@@ -8,7 +8,7 @@ import { useChat } from './hooks/useChat'
|
||||
import { HoverButton, SvgIcon } from '@/components/common'
|
||||
import { useBasicLayout } from '@/hooks/useBasicLayout'
|
||||
import { useChatStore } from '@/store'
|
||||
import { fetchChatAPI } from '@/api'
|
||||
import { fetchChatAPIProcess } from '@/api'
|
||||
|
||||
let controller = new AbortController()
|
||||
|
||||
@@ -82,21 +82,40 @@ async function onConversation() {
|
||||
scrollToBottom()
|
||||
|
||||
try {
|
||||
const { data } = await fetchChatAPI<Chat.ConversationResponse>(message, options, controller.signal)
|
||||
updateChat(
|
||||
+uuid,
|
||||
dataSources.value.length - 1,
|
||||
{
|
||||
dateTime: new Date().toLocaleString(),
|
||||
text: data.text ?? '',
|
||||
inversion: false,
|
||||
error: false,
|
||||
loading: false,
|
||||
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
|
||||
requestOptions: { prompt: message, options: { ...options } },
|
||||
await fetchChatAPIProcess<Chat.ConversationResponse>({
|
||||
prompt: message,
|
||||
options,
|
||||
signal: controller.signal,
|
||||
onDownloadProgress: ({ event }) => {
|
||||
const xhr = event.target
|
||||
const { responseText } = xhr
|
||||
// Always process the final line
|
||||
const lastIndex = responseText.lastIndexOf('\n')
|
||||
let chunk = responseText
|
||||
if (lastIndex !== -1)
|
||||
chunk = responseText.substring(lastIndex)
|
||||
try {
|
||||
const data = JSON.parse(chunk)
|
||||
updateChat(
|
||||
+uuid,
|
||||
dataSources.value.length - 1,
|
||||
{
|
||||
dateTime: new Date().toLocaleString(),
|
||||
text: data.text ?? '',
|
||||
inversion: false,
|
||||
error: false,
|
||||
loading: false,
|
||||
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
|
||||
requestOptions: { prompt: message, options: { ...options } },
|
||||
},
|
||||
)
|
||||
scrollToBottom()
|
||||
}
|
||||
catch (error) {
|
||||
//
|
||||
}
|
||||
},
|
||||
)
|
||||
scrollToBottom()
|
||||
})
|
||||
}
|
||||
catch (error: any) {
|
||||
let errorMessage = error?.message ?? 'Something went wrong, please try again later.'
|
||||
@@ -156,23 +175,42 @@ async function onRegenerate(index: number) {
|
||||
)
|
||||
|
||||
try {
|
||||
const { data } = await fetchChatAPI<Chat.ConversationResponse>(message, options, controller.signal)
|
||||
updateChat(
|
||||
+uuid,
|
||||
index,
|
||||
{
|
||||
dateTime: new Date().toLocaleString(),
|
||||
text: data.text ?? '',
|
||||
inversion: false,
|
||||
error: false,
|
||||
loading: false,
|
||||
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
|
||||
requestOptions: { prompt: message, ...options },
|
||||
await fetchChatAPIProcess<Chat.ConversationResponse>({
|
||||
prompt: message,
|
||||
options,
|
||||
signal: controller.signal,
|
||||
onDownloadProgress: ({ event }) => {
|
||||
const xhr = event.target
|
||||
const { responseText } = xhr
|
||||
// Always process the final line
|
||||
const lastIndex = responseText.lastIndexOf('\n')
|
||||
let chunk = responseText
|
||||
if (lastIndex !== -1)
|
||||
chunk = responseText.substring(lastIndex)
|
||||
try {
|
||||
const data = JSON.parse(chunk)
|
||||
updateChat(
|
||||
+uuid,
|
||||
index,
|
||||
{
|
||||
dateTime: new Date().toLocaleString(),
|
||||
text: data.text ?? '',
|
||||
inversion: false,
|
||||
error: false,
|
||||
loading: false,
|
||||
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
|
||||
requestOptions: { prompt: message, ...options },
|
||||
},
|
||||
)
|
||||
}
|
||||
catch (error) {
|
||||
//
|
||||
}
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
catch (error: any) {
|
||||
let errorMessage = 'Something went wrong, please try again later.'
|
||||
let errorMessage = error?.message ?? 'Something went wrong, please try again later.'
|
||||
|
||||
if (error.message === 'canceled')
|
||||
errorMessage = 'Request canceled. Please try again.'
|
||||
@@ -228,9 +266,11 @@ function handleClear() {
|
||||
}
|
||||
|
||||
function handleEnter(event: KeyboardEvent) {
|
||||
if (event.key === 'Enter' && !event.shiftKey) {
|
||||
event.preventDefault()
|
||||
handleSubmit()
|
||||
if (!isMobile.value) {
|
||||
if (event.key === 'Enter' && !event.shiftKey) {
|
||||
event.preventDefault()
|
||||
handleSubmit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,6 +281,12 @@ function handleStop() {
|
||||
}
|
||||
}
|
||||
|
||||
const placeholder = computed(() => {
|
||||
if (isMobile.value)
|
||||
return 'Ask me anything...'
|
||||
return 'Ask me anything... (Shift + Enter = line break)'
|
||||
})
|
||||
|
||||
const buttonDisabled = computed(() => {
|
||||
return loading.value || !prompt.value || prompt.value.trim() === ''
|
||||
})
|
||||
@@ -272,7 +318,12 @@ onUnmounted(() => {
|
||||
<template>
|
||||
<div class="flex flex-col h-full" :class="wrapClass">
|
||||
<main class="flex-1 overflow-hidden">
|
||||
<div ref="scrollRef" class="h-full p-4 overflow-hidden overflow-y-auto" :class="[{ 'p-2': isMobile }]">
|
||||
<div
|
||||
id="scrollRef"
|
||||
ref="scrollRef"
|
||||
class="h-full overflow-hidden overflow-y-auto"
|
||||
:class="[isMobile ? 'p-2' : 'p-4']"
|
||||
>
|
||||
<template v-if="!dataSources.length">
|
||||
<div class="flex items-center justify-center mt-4 text-center text-neutral-300">
|
||||
<SvgIcon icon="ri:bubble-chart-fill" class="mr-2 text-3xl" />
|
||||
@@ -315,7 +366,7 @@ onUnmounted(() => {
|
||||
v-model:value="prompt"
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 1, maxRows: 2 }"
|
||||
placeholder="Ask me anything..."
|
||||
:placeholder="placeholder"
|
||||
@keypress="handleEnter"
|
||||
/>
|
||||
<NButton type="primary" :disabled="buttonDisabled" @click="handleSubmit">
|
||||
|
@@ -1,5 +1,5 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed } from 'vue'
|
||||
import { computed, nextTick } from 'vue'
|
||||
import { SvgIcon } from '@/components/common'
|
||||
import { useAppStore, useChatStore } from '@/store'
|
||||
|
||||
@@ -7,25 +7,48 @@ const appStore = useAppStore()
|
||||
const chatStore = useChatStore()
|
||||
|
||||
const collapsed = computed(() => appStore.siderCollapsed)
|
||||
|
||||
function handleAdd() {
|
||||
chatStore.addHistory({ title: 'New Chat', uuid: Date.now(), isEdit: false })
|
||||
}
|
||||
const currentChatHistory = computed(() => chatStore.getChatHistoryByCurrentActive)
|
||||
|
||||
function handleUpdateCollapsed() {
|
||||
appStore.setSiderCollapsed(!collapsed.value)
|
||||
}
|
||||
|
||||
function onScrollToTop() {
|
||||
const scrollRef = document.querySelector('#scrollRef')
|
||||
if (scrollRef)
|
||||
nextTick(() => scrollRef.scrollTop = 0)
|
||||
}
|
||||
|
||||
function onScrollToBottom() {
|
||||
const scrollRef = document.querySelector('#scrollRef')
|
||||
if (scrollRef)
|
||||
nextTick(() => scrollRef.scrollTop = scrollRef.scrollHeight)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="fixed top-0 left-0 right-0 z-30 border-b dark:border-neutral-800 bg-white/80 dark:bg-black/30 backdrop-blur">
|
||||
<header
|
||||
class="fixed top-0 left-0 right-0 z-30 border-b dark:border-neutral-800 bg-white/80 dark:bg-black/20 backdrop-blur"
|
||||
>
|
||||
<div class="relative flex items-center justify-between h-14">
|
||||
<button class="flex items-center justify-center w-11 h-11" @click="handleUpdateCollapsed">
|
||||
<button
|
||||
class="flex items-center justify-center w-11 h-11"
|
||||
@click="handleUpdateCollapsed"
|
||||
>
|
||||
<SvgIcon v-if="collapsed" class="text-2xl" icon="ri:align-justify" />
|
||||
<SvgIcon v-else class="text-2xl" icon="ri:align-right" />
|
||||
</button>
|
||||
<button class="flex items-center justify-center w-11 h-11" @click="handleAdd">
|
||||
<SvgIcon class="text-2xl" icon="ri:add-fill" />
|
||||
<h1
|
||||
class="flex-1 px-4 overflow-hidden text-center cursor-pointer select-none text-ellipsis whitespace-nowrap"
|
||||
@dblclick="onScrollToTop"
|
||||
>
|
||||
{{ currentChatHistory?.title ?? '' }}
|
||||
</h1>
|
||||
<button
|
||||
class="flex items-center justify-center w-11 h-11"
|
||||
@click="onScrollToBottom"
|
||||
>
|
||||
<SvgIcon class="text-2xl" icon="ri:arrow-down-s-line" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
@@ -46,8 +46,8 @@ function handleThemeChange(key: 'light' | 'dark' | 'auto') {
|
||||
<NDropdown :options="options" placement="top" trigger="click" @select="handleThemeChange">
|
||||
<HoverButton>
|
||||
<span class="text-xl text-[#4f555e] dark:text-white">
|
||||
<SvgIcon v-if="theme === 'dark'" icon="ri:sun-foggy-line" />
|
||||
<SvgIcon v-if="theme === 'light'" icon="ri:moon-foggy-line" />
|
||||
<SvgIcon v-if="theme === 'dark'" icon="ri:moon-foggy-line" />
|
||||
<SvgIcon v-if="theme === 'light'" icon="ri:sun-foggy-line" />
|
||||
<SvgIcon v-if="theme === 'auto'" icon="ri:contrast-line" />
|
||||
</span>
|
||||
</HoverButton>
|
||||
|
Reference in New Issue
Block a user