mirror of
https://github.com/Chanzhaoyu/chatgpt-web.git
synced 2025-07-26 16:24:39 +00:00
Compare commits
105 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
e9db25a970 | ||
![]() |
63f4d7d77c | ||
![]() |
20255ddce4 | ||
![]() |
bbd8ff773b | ||
![]() |
c8518b7789 | ||
![]() |
bf015d35f7 | ||
![]() |
eab39b7f88 | ||
![]() |
981c036542 | ||
![]() |
91f51b6338 | ||
![]() |
26de5359ef | ||
![]() |
0423b87530 | ||
![]() |
58464b2cee | ||
![]() |
e23e1df3ce | ||
![]() |
2c3bc77eb2 | ||
![]() |
52b43868eb | ||
![]() |
7930ec5dab | ||
![]() |
7835740159 | ||
![]() |
c8745f2e21 | ||
![]() |
0b8b58f85c | ||
![]() |
c09a4f6c75 | ||
![]() |
d9761ed0e5 | ||
![]() |
cb8e2cf814 | ||
![]() |
f73aa5f9e1 | ||
![]() |
c617205a8c | ||
![]() |
79eeb51537 | ||
![]() |
b2977d8c44 | ||
![]() |
8dab963628 | ||
![]() |
79dd6c5e18 | ||
![]() |
da75ca944c | ||
![]() |
4458e744cc | ||
![]() |
d2ae2c4f54 | ||
![]() |
cf8e2dd7b6 | ||
![]() |
701ef0e6e1 | ||
![]() |
de34af8747 | ||
![]() |
33c02cfe10 | ||
![]() |
b03f804e35 | ||
![]() |
b6e5c59a9c | ||
![]() |
797cc7461b | ||
![]() |
58547d1b58 | ||
![]() |
c933a851f4 | ||
![]() |
86fcbbff0b | ||
![]() |
5d1f8519c2 | ||
![]() |
3c21068150 | ||
![]() |
cd03a71ef1 | ||
![]() |
1d74717beb | ||
![]() |
e35abb1c98 | ||
![]() |
b4b0f65158 | ||
![]() |
910c19b02e | ||
![]() |
32049fbf18 | ||
![]() |
817a4842ac | ||
![]() |
0cd120ec5b | ||
![]() |
007763f7d7 | ||
![]() |
3debaec4b2 | ||
![]() |
35f353c1f7 | ||
![]() |
3ac6746930 | ||
![]() |
9b556e4833 | ||
![]() |
071283c007 | ||
![]() |
854261ef86 | ||
![]() |
633e9ad8e2 | ||
![]() |
47dd6c9801 | ||
![]() |
0eb9df6d31 | ||
![]() |
8bfbe6f7df | ||
![]() |
43e8635e7f | ||
![]() |
b7542c70cb | ||
![]() |
b594ec5de1 | ||
![]() |
9a9b154040 | ||
![]() |
12681b1a05 | ||
![]() |
9f4f6304c7 | ||
![]() |
93c63d9195 | ||
![]() |
361494d444 | ||
![]() |
2f69cfd10b | ||
![]() |
0086f17df4 | ||
![]() |
befad1cbe1 | ||
![]() |
6cafc07e0d | ||
![]() |
feb167e2da | ||
![]() |
847623e22a | ||
![]() |
dd522eb404 | ||
![]() |
73c9ac4d8f | ||
![]() |
727562f495 | ||
![]() |
d7464642a7 | ||
![]() |
951636869b | ||
![]() |
39f718ef16 | ||
![]() |
72df35c929 | ||
![]() |
cf7a56a015 | ||
![]() |
5ca1b4557a | ||
![]() |
11544ff24b | ||
![]() |
f910b5f8a4 | ||
![]() |
98e75c0c5c | ||
![]() |
06fd5a861c | ||
![]() |
fc0d2073aa | ||
![]() |
2c816afbd2 | ||
![]() |
1bf2399a45 | ||
![]() |
ddec57f562 | ||
![]() |
63af4a8e97 | ||
![]() |
a5a67f688e | ||
![]() |
692d37ec35 | ||
![]() |
4b16560958 | ||
![]() |
52bfd15ad8 | ||
![]() |
e0920bee4b | ||
![]() |
cb589e05e9 | ||
![]() |
6aa2591d9c | ||
![]() |
ad41dd21c6 | ||
![]() |
35da3f1d1f | ||
![]() |
31ea7c5529 | ||
![]() |
cab7b0ec99 |
3
.commitlintrc.json
Normal file
3
.commitlintrc.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": ["@commitlint/config-conventional"]
|
||||
}
|
7
.env
7
.env
@@ -1,5 +1,4 @@
|
||||
# OpenAI API Key
|
||||
OPENAI_API_KEY='xxxx'
|
||||
|
||||
# Glob API URL
|
||||
VITE_GLOB_API_URL='http://localhost:3002'
|
||||
VITE_GLOB_API_URL=/api
|
||||
|
||||
VITE_APP_API_BASE_URL=http://localhost:3002/
|
||||
|
@@ -1 +0,0 @@
|
||||
components.d.ts
|
47
.github/workflows/ci.yml
vendored
Normal file
47
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,47 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Set node
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 18.x
|
||||
|
||||
- name: Setup
|
||||
run: npm i -g @antfu/ni
|
||||
|
||||
- name: Install
|
||||
run: nci
|
||||
|
||||
- name: Lint
|
||||
run: nr lint:fix
|
||||
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Set node
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 18.x
|
||||
|
||||
- name: Setup
|
||||
run: npm i -g @antfu/ni
|
||||
|
||||
- name: Install
|
||||
run: nci
|
||||
|
||||
- name: Typecheck
|
||||
run: nr type-check
|
4
.husky/commit-msg
Executable file
4
.husky/commit-msg
Executable file
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
npx --no -- commitlint --edit
|
4
.husky/pre-commit
Executable file
4
.husky/pre-commit
Executable file
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
npx lint-staged
|
3
.npmrc
3
.npmrc
@@ -1,4 +1 @@
|
||||
registry=https://registry.npmmirror.com/
|
||||
shamefully-hoist=true
|
||||
strict-peer-dependencies=false
|
||||
auto-install-peers=true
|
||||
|
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"semi": false,
|
||||
"singleQuote": true
|
||||
}
|
2
.vscode/extensions.json
vendored
2
.vscode/extensions.json
vendored
@@ -1,3 +1,3 @@
|
||||
{
|
||||
"recommendations": ["Vue.volar", "Vue.vscode-typescript-vue-plugin"]
|
||||
"recommendations": ["Vue.volar", "dbaeumer.vscode-eslint"]
|
||||
}
|
||||
|
22
.vscode/settings.json
vendored
22
.vscode/settings.json
vendored
@@ -1,13 +1,29 @@
|
||||
{
|
||||
"prettier.enable": false,
|
||||
"editor.formatOnSave": false,
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.eslint": true
|
||||
},
|
||||
"eslint.validate": [
|
||||
"javascript",
|
||||
"javascriptreact",
|
||||
"typescript",
|
||||
"typescriptreact",
|
||||
"vue",
|
||||
"html",
|
||||
"json",
|
||||
"jsonc",
|
||||
"json5",
|
||||
"yaml",
|
||||
"yml",
|
||||
"markdown"
|
||||
],
|
||||
"cSpell.words": [
|
||||
"antfu",
|
||||
"axios",
|
||||
"bumpp",
|
||||
"chatgpt",
|
||||
"commitlint",
|
||||
"esno",
|
||||
"GPTAPI",
|
||||
"iconify",
|
||||
@@ -15,9 +31,13 @@
|
||||
"OPENAI",
|
||||
"pinia",
|
||||
"rushstack",
|
||||
"Sider",
|
||||
"tailwindcss",
|
||||
"tsup",
|
||||
"Typecheck",
|
||||
"unplugin",
|
||||
"VITE",
|
||||
"vueuse"
|
||||
"vueuse",
|
||||
"Zhao"
|
||||
]
|
||||
}
|
||||
|
92
CHANGELOG.md
92
CHANGELOG.md
@@ -0,0 +1,92 @@
|
||||
## v2.3.2
|
||||
|
||||
`2023-02-16`
|
||||
|
||||
### Enhancement
|
||||
- 更新依赖至最新
|
||||
- 优化部份内容
|
||||
|
||||
## v2.3.1
|
||||
|
||||
`2023-02-15`
|
||||
|
||||
### BugFix
|
||||
- 修复多会话状态下一些意想不到的问题
|
||||
|
||||
## v2.3.0
|
||||
|
||||
`2023-02-15`
|
||||
### Feature
|
||||
- 代码类型信息高亮显示
|
||||
- 支持 `node ^16` 版本
|
||||
- 移动端响应式初步支持
|
||||
- `vite` 中 `proxy` 代理
|
||||
|
||||
### Enhancement
|
||||
- 调整超时处理范围
|
||||
|
||||
### BugFix
|
||||
- 修复取消请求错误提示会添加到信息中
|
||||
- 修复部份情况下提交请求不可用
|
||||
- 修复侧边栏宽度变化闪烁的问题
|
||||
|
||||
## v2.2.0
|
||||
|
||||
`2023-02-14`
|
||||
### Feature
|
||||
- 会话和上下文本地储存
|
||||
- 侧边栏本地储存
|
||||
|
||||
## v2.1.0
|
||||
|
||||
`2023-02-14`
|
||||
### Enhancement
|
||||
- 更新依赖至最新
|
||||
- 联想功能移动至前端提交,后端只做转发
|
||||
|
||||
### BugFix
|
||||
- 修复部份项目检测有关 `Bug`
|
||||
- 修复清除上下文按钮失效
|
||||
|
||||
## v2.0.0
|
||||
|
||||
`2023-02-13`
|
||||
### Refactor
|
||||
重构并优化大部分内容
|
||||
|
||||
## v1.0.5
|
||||
|
||||
`2023-02-12`
|
||||
|
||||
### Enhancement
|
||||
- 输入框焦点,连续提交
|
||||
|
||||
### BugFix
|
||||
- 修复信息框样式问题
|
||||
- 修复中文输入法提交问题
|
||||
|
||||
## v1.0.4
|
||||
|
||||
`2023-02-11`
|
||||
|
||||
### Feature
|
||||
- 支持上下文联想
|
||||
|
||||
## v1.0.3
|
||||
|
||||
`2023-02-11`
|
||||
|
||||
### Enhancement
|
||||
- 拆分 `service` 文件以便扩展
|
||||
- 调整 `Eslint` 相关验证
|
||||
|
||||
### BugFix
|
||||
- 修复部份控制台报错
|
||||
|
||||
## v1.0.2
|
||||
|
||||
`2023-02-10`
|
||||
|
||||
### BugFix
|
||||
- 修复新增信息容器不会自动滚动到问题
|
||||
- 修复文本过长不换行到问题 [#1](https://github.com/Chanzhaoyu/chatgpt-web/issues/1)
|
||||
|
49
CONTRIBUTING.md
Normal file
49
CONTRIBUTING.md
Normal file
@@ -0,0 +1,49 @@
|
||||
# 贡献指南
|
||||
感谢你的宝贵时间。你的贡献将使这个项目变得更好!在提交贡献之前,请务必花点时间阅读下面的入门指南。
|
||||
|
||||
## 语义化版本
|
||||
该项目遵循语义化版本。我们对重要的漏洞修复发布修订号,对新特性或不重要的变更发布次版本号,对重大且不兼容的变更发布主版本号。
|
||||
|
||||
每个重大更改都将记录在 `changelog` 中。
|
||||
|
||||
## 提交 Pull Request
|
||||
1. Fork [此仓库](https://github.com/Chanzhaoyu/chatgpt-web),从 `main` 创建分支。新功能实现请发 pull request 到 `feature` 分支。其他更改发到 `main` 分支。
|
||||
2. 使用 `npm install pnpm -g` 安装 `pnpm` 工具。
|
||||
3. `vscode` 安装了 `Eslint` 插件,其它编辑器如 `webStorm` 打开了 `eslint` 功能。
|
||||
4. 根目录下执行 `pnpm bootstrap`。
|
||||
5. `/service/` 目录下执行 `pnpm install`。
|
||||
6. 对代码库进行更改。如果适用的话,请确保进行了相应的测试。
|
||||
7. 请在根目录下执行 `pnpm lint:fix` 进行代码格式检查。
|
||||
8. 请在根目录下执行 `pnpm type-check` 进行类型检查。
|
||||
9. 提交 git commit, 请同时遵守 [Commit 规范](#commit-指南)
|
||||
10. 提交 `pull request`, 如果有对应的 `issue`,请进行[关联](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword)。
|
||||
|
||||
## Commit 指南
|
||||
|
||||
Commit messages 请遵循[conventional-changelog 标准](https://www.conventionalcommits.org/en/v1.0.0/):
|
||||
|
||||
```bash
|
||||
<类型>[可选 范围]: <描述>
|
||||
|
||||
[可选 正文]
|
||||
|
||||
[可选 脚注]
|
||||
```
|
||||
|
||||
### Commit 类型
|
||||
|
||||
以下是 commit 类型列表:
|
||||
|
||||
- feat: 新特性或功能
|
||||
- fix: 缺陷修复
|
||||
- docs: 文档更新
|
||||
- style: 代码风格或者组件样式更新
|
||||
- refactor: 代码重构,不引入新功能和缺陷修复
|
||||
- perf: 性能优化
|
||||
- test: 单元测试
|
||||
- chore: 其他不修改 src 或测试文件的提交
|
||||
|
||||
|
||||
## License
|
||||
|
||||
[MIT](./license)
|
120
README.md
120
README.md
@@ -1,39 +1,121 @@
|
||||
# ChatGPT Web Bot
|
||||
# ChatGPT Web
|
||||
|
||||
English | [中文](./README.zh-CN.md)
|
||||
使用 express 和 vue3 搭建的 ChartGPT 演示网页
|
||||
|
||||
ChartGPT demo page built with express and vue3
|
||||

|
||||
|
||||

|
||||
## Usage
|
||||
> Make sure `node >= 18`
|
||||
> 提示:目前 `OpenAI` 开放的模型最高只有 `GPT-3`,和现在网页所使用的 `GPT-3.5` 或 `GPT-4` 有很大差距,需要等官方开放最新的模型接口。
|
||||
|
||||
If pnpm is not installed
|
||||
## 待实现路线
|
||||
[✓] 多会话储存和上下文逻辑
|
||||
|
||||
[✓] 对代码等消息类型的格式化美化处理
|
||||
|
||||
[✗] 用户模块(注册、登录、个人中心)
|
||||
|
||||
[✗] 界面多语言
|
||||
|
||||
[✗] 界面主题
|
||||
|
||||
[✗] More...
|
||||
|
||||
## 前置要求
|
||||
|
||||
### Node
|
||||
|
||||
`node` 需要 `^16 || ^18` 版本(或者 `node >= 14` 需要安装 [fetch polyfill](https://github.com/developit/unfetch#usage-as-a-polyfill)),使用 [nvm](https://github.com/nvm-sh/nvm) 可管理本地多个 `node` 版本
|
||||
|
||||
```shell
|
||||
node -v
|
||||
```
|
||||
|
||||
### PNPM
|
||||
如果你没有安装过 `pnpm`
|
||||
```shell
|
||||
npm install pnpm -g
|
||||
```
|
||||
|
||||
install node deps
|
||||
### OpenAI API Key
|
||||
注册并获取 [OpenAI API key](https://platform.openai.com/overview) 并填写到本地环境变量
|
||||
```
|
||||
# service/.env 文件
|
||||
|
||||
OPENAI_API_KEY='Your key'
|
||||
```
|
||||
|
||||
## 安装依赖
|
||||
|
||||
> 为了简便 `后端开发人员` 的了解负担,所以并没有采用前端 `workspace` 模式,而是分文件夹存放。如果只需要前端页面做二次开发,删除 `service` 文件夹即可。
|
||||
|
||||
### 后端服务
|
||||
|
||||
进入文件夹 `/service` 运行以下命令
|
||||
|
||||
```shell
|
||||
pnpm install
|
||||
```
|
||||
|
||||
Sign up for an [OpenAI API key](https://platform.openai.com/overview) and store it in your environment.
|
||||
|
||||
```
|
||||
# .env
|
||||
OPENAI_API_KEY="Your Key"
|
||||
```
|
||||
|
||||
Run service
|
||||
### 网页
|
||||
根目录下运行以下命令
|
||||
```shell
|
||||
pnpm run service
|
||||
pnpm bootstrap
|
||||
```
|
||||
|
||||
Run web
|
||||
|
||||
## 运行
|
||||
### 后端服务
|
||||
|
||||
进入文件夹 `/service` 运行以下命令
|
||||
|
||||
```shell
|
||||
pnpm run dev
|
||||
pnpm start
|
||||
```
|
||||
|
||||
### 网页
|
||||
根目录下运行以下命令
|
||||
```shell
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
## 打包
|
||||
|
||||
### 后端服务
|
||||
> 如果你不需要本项目的 `node` 接口,可以省略如下操作
|
||||
|
||||
复制 `service` 文件夹到你有 `node` 服务环境的服务器上。(搜索关键字:`express部署`)
|
||||
|
||||
```shell
|
||||
# 安装
|
||||
pnpm install
|
||||
|
||||
# 打包
|
||||
pnpm build
|
||||
|
||||
# 运行
|
||||
pnpm prod
|
||||
```
|
||||
|
||||
PS: 不进行打包,直接在服务器上运行 `pnpm start` 也可
|
||||
|
||||
### 网页
|
||||
根目录下运行以下命令,然后将 `dist` 文件夹复制到你的托管服务器上
|
||||
|
||||
```shell
|
||||
pnpm build
|
||||
```
|
||||
|
||||
### 常见问题
|
||||
Q: 为什么 `Git` 提交总是报错?
|
||||
|
||||
A: 因为有提交信息验证,请遵循 [Commit 指南](./CONTRIBUTING.md)
|
||||
|
||||
Q: 如果只使用前端页面,在哪里改请求接口?
|
||||
|
||||
A: 根目录下 `.env` 文件中的 `VITE_GLOB_API_URL` 字段。
|
||||
|
||||
Q: 文件保存时全部爆红?
|
||||
|
||||
A: `vscode` 请安装项目推荐插件,或手动安装 `Eslint` 插件。
|
||||
|
||||
## License
|
||||
MIT © [ChenZhaoYu](./license)
|
||||
|
@@ -1,40 +0,0 @@
|
||||
# ChatGPT Web Bot
|
||||
|
||||
[English](./README.md) | 中文
|
||||
|
||||
使用 express 和 vue3 搭建的 ChartGPT 演示网页
|
||||
|
||||

|
||||
|
||||
## 使用
|
||||
> Make sure `node >= 18`
|
||||
|
||||
如果你没有安装过 `pnpm`
|
||||
```shell
|
||||
npm install pnpm -g
|
||||
```
|
||||
|
||||
安装依赖
|
||||
```shell
|
||||
pnpm install
|
||||
```
|
||||
|
||||
获取 [OpenAI API key](https://platform.openai.com/overview) 到本地环境变量
|
||||
|
||||
```
|
||||
# .env
|
||||
OPENAI_API_KEY="Your Key"
|
||||
```
|
||||
|
||||
运行服务
|
||||
```shell
|
||||
pnpm run service
|
||||
```
|
||||
|
||||
运行网页
|
||||
```shell
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
## License
|
||||
MIT © [ChenZhaoYu](./license)
|
BIN
docs/cover-2.png
Normal file
BIN
docs/cover-2.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 200 KiB |
BIN
docs/cover.png
BIN
docs/cover.png
Binary file not shown.
Before Width: | Height: | Size: 94 KiB |
125
index.html
125
index.html
@@ -1,71 +1,76 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-cmn-Hans">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>ChatGPT Web</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<style>
|
||||
.loading-wrap {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.balls {
|
||||
width: 4em;
|
||||
display: flex;
|
||||
flex-flow: row nowrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
||||
<meta name="viewport"
|
||||
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover" />
|
||||
<title>ChatGPT Web</title>
|
||||
</head>
|
||||
|
||||
.balls div {
|
||||
width: 0.8em;
|
||||
height: 0.8em;
|
||||
border-radius: 50%;
|
||||
background-color: #4b9e5f;
|
||||
}
|
||||
<body>
|
||||
<div id="app">
|
||||
<style>
|
||||
.loading-wrap {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.balls div:nth-of-type(1) {
|
||||
transform: translateX(-100%);
|
||||
animation: left-swing 0.5s ease-in alternate infinite;
|
||||
}
|
||||
.balls {
|
||||
width: 4em;
|
||||
display: flex;
|
||||
flex-flow: row nowrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.balls div:nth-of-type(3) {
|
||||
transform: translateX(-95%);
|
||||
animation: right-swing 0.5s ease-out alternate infinite;
|
||||
}
|
||||
.balls div {
|
||||
width: 0.8em;
|
||||
height: 0.8em;
|
||||
border-radius: 50%;
|
||||
background-color: #4b9e5f;
|
||||
}
|
||||
|
||||
@keyframes left-swing {
|
||||
50%,
|
||||
100% {
|
||||
transform: translateX(95%);
|
||||
}
|
||||
}
|
||||
.balls div:nth-of-type(1) {
|
||||
transform: translateX(-100%);
|
||||
animation: left-swing 0.5s ease-in alternate infinite;
|
||||
}
|
||||
|
||||
@keyframes right-swing {
|
||||
50% {
|
||||
transform: translateX(-95%);
|
||||
}
|
||||
.balls div:nth-of-type(3) {
|
||||
transform: translateX(-95%);
|
||||
animation: right-swing 0.5s ease-out alternate infinite;
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<div class="loading-wrap">
|
||||
<div class="balls">
|
||||
<div></div>
|
||||
<div></div>
|
||||
<div></div>
|
||||
</div>
|
||||
</div>
|
||||
@keyframes left-swing {
|
||||
|
||||
50%,
|
||||
100% {
|
||||
transform: translateX(95%);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes right-swing {
|
||||
50% {
|
||||
transform: translateX(-95%);
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<div class="loading-wrap">
|
||||
<div class="balls">
|
||||
<div></div>
|
||||
<div></div>
|
||||
<div></div>
|
||||
</div>
|
||||
</div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
104
package.json
104
package.json
@@ -1,50 +1,58 @@
|
||||
{
|
||||
"name": "chatgpt-web",
|
||||
"version": "1.0.2",
|
||||
"description": "ChatGPT Web Bot",
|
||||
"author": "ChenZhaoYu <chenzhaoyu1994@gami.com>",
|
||||
"private": false,
|
||||
"keywords": [
|
||||
"chatgpt",
|
||||
"chatbot",
|
||||
"web",
|
||||
"vue"
|
||||
],
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"service": "esno ./service/index.ts",
|
||||
"build": "run-p type-check build-only",
|
||||
"preview": "vite preview",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --noEmit",
|
||||
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
|
||||
"release": "bumpp package.json --commit --push --tag"
|
||||
},
|
||||
"dependencies": {
|
||||
"naive-ui": "^2.34.3",
|
||||
"vue": "^3.2.45"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^0.35.2",
|
||||
"@iconify/vue": "^4.1.0",
|
||||
"@types/babel__core": "^7.20.0",
|
||||
"@types/express": "^4.17.17",
|
||||
"@types/node": "^18.11.12",
|
||||
"@vitejs/plugin-vue": "^4.0.0",
|
||||
"autoprefixer": "^10.4.13",
|
||||
"axios": "^1.3.2",
|
||||
"bumpp": "^8.2.1",
|
||||
"chatgpt": "^4.2.0",
|
||||
"dotenv": "^16.0.3",
|
||||
"eslint": "^8.22.0",
|
||||
"esno": "^0.16.3",
|
||||
"express": "^4.18.2",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"postcss": "^8.4.21",
|
||||
"prettier": "^2.7.1",
|
||||
"tailwindcss": "^3.2.6",
|
||||
"typescript": "~4.7.4",
|
||||
"vite": "^4.0.0",
|
||||
"vue-tsc": "^1.0.12"
|
||||
}
|
||||
"name": "chatgpt-web",
|
||||
"version": "2.3.2",
|
||||
"private": false,
|
||||
"description": "ChatGPT Web",
|
||||
"author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>",
|
||||
"keywords": [
|
||||
"chatgpt-web",
|
||||
"chatgpt",
|
||||
"chatbot",
|
||||
"vue"
|
||||
],
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "run-p type-check build-only",
|
||||
"preview": "vite preview",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --noEmit",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"bootstrap": "pnpm install && pnpm run common:prepare",
|
||||
"common:cleanup": "rimraf node_modules && rimraf pnpm-lock.yaml",
|
||||
"common:prepare": "husky install"
|
||||
},
|
||||
"dependencies": {
|
||||
"highlight.js": "^11.7.0",
|
||||
"naive-ui": "^2.34.3",
|
||||
"pinia": "^2.0.30",
|
||||
"vue": "^3.2.47",
|
||||
"vue-router": "^4.1.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^0.35.2",
|
||||
"@commitlint/cli": "^17.4.3",
|
||||
"@commitlint/config-conventional": "^17.4.3",
|
||||
"@iconify/vue": "^4.1.0",
|
||||
"@types/crypto-js": "^4.1.1",
|
||||
"@types/node": "^18.13.0",
|
||||
"@vitejs/plugin-vue": "^4.0.0",
|
||||
"autoprefixer": "^10.4.13",
|
||||
"axios": "^1.3.3",
|
||||
"crypto-js": "^4.1.1",
|
||||
"eslint": "^8.34.0",
|
||||
"husky": "^8.0.3",
|
||||
"lint-staged": "^13.1.2",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"postcss": "^8.4.21",
|
||||
"rimraf": "^4.1.2",
|
||||
"tailwindcss": "^3.2.6",
|
||||
"typescript": "~4.9.5",
|
||||
"vite": "^4.1.1",
|
||||
"vue-tsc": "^1.1.0"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{ts,tsx,vue}": [
|
||||
"pnpm lint:fix"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
2264
pnpm-lock.yaml
generated
2264
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
2
service/.env
Normal file
2
service/.env
Normal file
@@ -0,0 +1,2 @@
|
||||
# OpenAI API Key - https://platform.openai.com/overview
|
||||
OPENAI_API_KEY=
|
5
service/.eslintrc.json
Normal file
5
service/.eslintrc.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"root": true,
|
||||
"ignorePatterns": ["build"],
|
||||
"extends": ["@antfu"]
|
||||
}
|
31
service/.gitignore
vendored
Normal file
31
service/.gitignore
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
build
|
1
service/.npmrc
Normal file
1
service/.npmrc
Normal file
@@ -0,0 +1 @@
|
||||
enable-pre-post-scripts=true
|
3
service/.vscode/extensions.json
vendored
Normal file
3
service/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["dbaeumer.vscode-eslint"]
|
||||
}
|
22
service/.vscode/settings.json
vendored
Normal file
22
service/.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"prettier.enable": false,
|
||||
"editor.formatOnSave": false,
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.eslint": true
|
||||
},
|
||||
"eslint.validate": [
|
||||
"javascript",
|
||||
"typescript",
|
||||
"json",
|
||||
"jsonc",
|
||||
"json5",
|
||||
"yaml"
|
||||
],
|
||||
"cSpell.words": [
|
||||
"antfu",
|
||||
"chatgpt",
|
||||
"esno",
|
||||
"GPTAPI",
|
||||
"OPENAI"
|
||||
]
|
||||
}
|
@@ -1,41 +0,0 @@
|
||||
import dotenv from 'dotenv'
|
||||
import { ChatGPTAPI } from 'chatgpt'
|
||||
import express from 'express'
|
||||
|
||||
dotenv.config()
|
||||
|
||||
const app = express()
|
||||
|
||||
app.use(express.json())
|
||||
|
||||
async function chatAPI(message: string) {
|
||||
if (!message)
|
||||
throw new Error('Message is not defined')
|
||||
|
||||
if (!process.env.OPENAI_API_KEY)
|
||||
throw new Error('OPENAI_API_KEY is not defined in .env file')
|
||||
|
||||
try {
|
||||
const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
|
||||
const res = await api.sendMessage(message)
|
||||
return res
|
||||
}
|
||||
catch (error) {
|
||||
return error
|
||||
}
|
||||
}
|
||||
|
||||
app.all('*', (req, res, next) => {
|
||||
res.header('Access-Control-Allow-Origin', '*')
|
||||
res.header('Access-Control-Allow-Headers', 'Content-Type')
|
||||
res.header('Access-Control-Allow-Methods', '*')
|
||||
next()
|
||||
})
|
||||
|
||||
app.listen(3002, () => globalThis.console.log('Server is running on port 3002'))
|
||||
|
||||
app.post('/chat', async (req, res) => {
|
||||
const { message } = req.body
|
||||
const response = await chatAPI(message)
|
||||
res.send(response)
|
||||
})
|
41
service/package.json
Normal file
41
service/package.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "chatgpt-web-service",
|
||||
"version": "1.0.0",
|
||||
"private": false,
|
||||
"description": "ChatGPT Web Service",
|
||||
"author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>",
|
||||
"keywords": [
|
||||
"chatgpt-web",
|
||||
"chatgpt",
|
||||
"chatbot",
|
||||
"express"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^16 || ^18"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "esno ./src/index.ts",
|
||||
"prod": "esno ./build/index.js",
|
||||
"build": "pnpm clean && tsup",
|
||||
"clean": "rimraf build",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"common:cleanup": "rimraf node_modules && rimraf pnpm-lock.yaml"
|
||||
},
|
||||
"dependencies": {
|
||||
"chatgpt": "^4.4.1",
|
||||
"dotenv": "^16.0.3",
|
||||
"esno": "^0.16.3",
|
||||
"express": "^4.18.2",
|
||||
"isomorphic-fetch": "^3.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^0.35.2",
|
||||
"@types/express": "^4.17.17",
|
||||
"@types/node": "^18.13.0",
|
||||
"eslint": "^8.34.0",
|
||||
"rimraf": "^4.1.2",
|
||||
"tsup": "^6.6.3",
|
||||
"typescript": "^4.9.5"
|
||||
}
|
||||
}
|
3403
service/pnpm-lock.yaml
generated
Normal file
3403
service/pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
49
service/src/chatgpt.ts
Normal file
49
service/src/chatgpt.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import * as dotenv from 'dotenv'
|
||||
import 'isomorphic-fetch'
|
||||
import type { ChatGPTAPI, SendMessageOptions } from 'chatgpt'
|
||||
import { sendResponse } from './utils'
|
||||
|
||||
export interface ChatContext {
|
||||
conversationId?: string
|
||||
parentMessageId?: string
|
||||
}
|
||||
|
||||
dotenv.config()
|
||||
|
||||
const apiKey = process.env.OPENAI_API_KEY
|
||||
|
||||
if (apiKey === undefined)
|
||||
throw new Error('OPENAI_API_KEY is not defined')
|
||||
|
||||
let api: ChatGPTAPI
|
||||
|
||||
// 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')
|
||||
api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
|
||||
})()
|
||||
|
||||
async function chatReply(
|
||||
message: string,
|
||||
lastContext?: { conversationId?: string; parentMessageId?: string },
|
||||
) {
|
||||
if (!message)
|
||||
return sendResponse({ type: 'Fail', message: 'Message is empty' })
|
||||
|
||||
try {
|
||||
let options: SendMessageOptions = { timeoutMs: 30 * 1000 }
|
||||
|
||||
if (lastContext)
|
||||
options = { ...lastContext }
|
||||
|
||||
const response = await api.sendMessage(message, { ...options })
|
||||
|
||||
return sendResponse({ type: 'Success', data: response })
|
||||
}
|
||||
catch (error: any) {
|
||||
return sendResponse({ type: 'Fail', message: error.message })
|
||||
}
|
||||
}
|
||||
|
||||
export { chatReply }
|
32
service/src/index.ts
Normal file
32
service/src/index.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import express from 'express'
|
||||
import type { ChatContext } from './chatgpt'
|
||||
import { chatReply } from './chatgpt'
|
||||
|
||||
const app = express()
|
||||
const router = express.Router()
|
||||
|
||||
app.use(express.static('public'))
|
||||
app.use(express.json())
|
||||
|
||||
app.all('*', (_, res, next) => {
|
||||
res.header('Access-Control-Allow-Origin', '*')
|
||||
res.header('Access-Control-Allow-Headers', 'Content-Type')
|
||||
res.header('Access-Control-Allow-Methods', '*')
|
||||
next()
|
||||
})
|
||||
|
||||
router.post('/chat', async (req, res) => {
|
||||
try {
|
||||
const { prompt, options = {} } = req.body as { prompt: string; options?: ChatContext }
|
||||
const response = await chatReply(prompt, options)
|
||||
res.send(response)
|
||||
}
|
||||
catch (error) {
|
||||
res.send(error)
|
||||
}
|
||||
})
|
||||
|
||||
app.use('', router)
|
||||
app.use('/api', router)
|
||||
|
||||
app.listen(3002, () => globalThis.console.log('Server is running on port 3002'))
|
22
service/src/utils/index.ts
Normal file
22
service/src/utils/index.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
interface SendResponseOptions {
|
||||
type: 'Success' | 'Fail'
|
||||
message?: string
|
||||
data?: any
|
||||
}
|
||||
|
||||
export function sendResponse(options: SendResponseOptions) {
|
||||
if (options.type === 'Success') {
|
||||
return Promise.resolve({
|
||||
message: options.message ?? null,
|
||||
data: options.data ?? null,
|
||||
status: options.type,
|
||||
})
|
||||
}
|
||||
|
||||
// eslint-disable-next-line prefer-promise-reject-errors
|
||||
return Promise.reject({
|
||||
message: options.message ?? 'Failed',
|
||||
data: options.data ?? null,
|
||||
status: options.type,
|
||||
})
|
||||
}
|
27
service/tsconfig.json
Normal file
27
service/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2020",
|
||||
"lib": [
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": false,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"baseUrl": ".",
|
||||
"outDir": "build",
|
||||
"noEmit": true
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"build"
|
||||
],
|
||||
"include": [
|
||||
"**/*.ts"
|
||||
]
|
||||
}
|
13
service/tsup.config.ts
Normal file
13
service/tsup.config.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'tsup'
|
||||
|
||||
export default defineConfig({
|
||||
entry: ['src/index.ts'],
|
||||
outDir: 'build',
|
||||
target: 'es2020',
|
||||
format: ['cjs'],
|
||||
splitting: false,
|
||||
sourcemap: true,
|
||||
minify: false,
|
||||
shims: true,
|
||||
dts: false,
|
||||
})
|
15
src/App.vue
15
src/App.vue
@@ -1,13 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { GithubSite, NaiveProvider } from '@/components'
|
||||
import Chat from '@/views/Chat/index.vue'
|
||||
import { NConfigProvider } from 'naive-ui'
|
||||
import { NaiveProvider } from '@/components/common'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NaiveProvider>
|
||||
<div class="h-full overflow-hidden pb-[50px] p-4">
|
||||
<Chat />
|
||||
<GithubSite />
|
||||
</div>
|
||||
</NaiveProvider>
|
||||
<NConfigProvider class="h-full">
|
||||
<NaiveProvider>
|
||||
<RouterView />
|
||||
</NaiveProvider>
|
||||
</NConfigProvider>
|
||||
</template>
|
||||
|
14
src/api/index.ts
Normal file
14
src/api/index.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import type { GenericAbortSignal } from 'axios'
|
||||
import { post } from '@/utils/request'
|
||||
|
||||
export function fetchChatAPI<T = any>(
|
||||
prompt: string,
|
||||
options?: { conversationId?: string; parentMessageId?: string },
|
||||
signal?: GenericAbortSignal,
|
||||
) {
|
||||
return post<T>({
|
||||
url: '/chat',
|
||||
data: { prompt, options },
|
||||
signal,
|
||||
})
|
||||
}
|
@@ -1,10 +0,0 @@
|
||||
<template>
|
||||
<div class="fixed bottom-0 left-0 right-0 p-4 text-sm text-center text-neutral-500">
|
||||
<span class="text-center">
|
||||
❤️ Made By ChenZhaoYu -
|
||||
<a href="https://github.com/Chanzhaoyu/chatgpt-bot" target="_blank" class="text-blue-500">
|
||||
Github
|
||||
</a>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
@@ -1,27 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { defineComponent, h } from 'vue'
|
||||
import { NConfigProvider, NMessageProvider, useMessage } from 'naive-ui'
|
||||
|
||||
function registerNaiveTools() {
|
||||
window.$message = useMessage()
|
||||
}
|
||||
|
||||
const NaiveProviderContent = defineComponent({
|
||||
name: 'NaiveProviderContent',
|
||||
setup() {
|
||||
registerNaiveTools()
|
||||
},
|
||||
render() {
|
||||
return h('div')
|
||||
},
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NConfigProvider class="h-full">
|
||||
<NMessageProvider>
|
||||
<slot />
|
||||
<NaiveProviderContent />
|
||||
</NMessageProvider>
|
||||
</NConfigProvider>
|
||||
</template>
|
22
src/components/business/Chat/components/Message/Text.vue
Normal file
22
src/components/business/Chat/components/Message/Text.vue
Normal file
@@ -0,0 +1,22 @@
|
||||
<script lang="ts" setup>
|
||||
interface Props {
|
||||
reversal?: boolean
|
||||
error?: boolean
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="p-2 mt-2 rounded-md" :class="[reversal ? 'bg-[#d2f9d1]' : 'bg-[#f4f6f8]']">
|
||||
<span v-highlight class="leading-relaxed whitespace-pre-wrap">
|
||||
<slot />
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
.hljs {
|
||||
background-color: #fff0 !important;
|
||||
}
|
||||
</style>
|
@@ -6,6 +6,7 @@ interface Props {
|
||||
message?: string
|
||||
dateTime?: string
|
||||
reversal?: boolean
|
||||
error?: boolean
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
@@ -19,13 +20,13 @@ defineProps<Props>()
|
||||
>
|
||||
<Avatar :image="reversal" />
|
||||
</div>
|
||||
<div class="flex flex-col flex-1 text-sm" :class="[{ 'items-end': reversal }]">
|
||||
<div class="flex flex-col flex-1 text-sm" :class="[reversal ? 'items-end' : 'items-start']">
|
||||
<span class="text-xs text-[#b4bbc4]">
|
||||
{{ dateTime }}
|
||||
</span>
|
||||
<div class="p-2 mt-2 rounded-md" :class="[reversal ? 'bg-[#d2f9d1]' : 'bg-[#f4f6f8]']">
|
||||
<Text>{{ message }}</Text>
|
||||
</div>
|
||||
<Text :reversal="reversal" :error="error">
|
||||
{{ message }}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
26
src/components/business/Chat/hooks/useChat.ts
Normal file
26
src/components/business/Chat/hooks/useChat.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { useHistoryStore } from '@/store'
|
||||
|
||||
export function useChat() {
|
||||
const historyStore = useHistoryStore()
|
||||
|
||||
function addChat(
|
||||
message: string,
|
||||
args?: { reversal?: boolean; error?: boolean; options?: Chat.ChatOptions },
|
||||
) {
|
||||
historyStore.addChat(
|
||||
{
|
||||
dateTime: new Date().toLocaleString(),
|
||||
message,
|
||||
reversal: args?.reversal ?? false,
|
||||
error: args?.error ?? false,
|
||||
options: args?.options ?? undefined,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
function clearChat() {
|
||||
historyStore.clearChat()
|
||||
}
|
||||
|
||||
return { addChat, clearChat }
|
||||
}
|
147
src/components/business/Chat/index.vue
Normal file
147
src/components/business/Chat/index.vue
Normal file
@@ -0,0 +1,147 @@
|
||||
<script setup lang='ts'>
|
||||
import { computed, nextTick, onMounted, ref, watch } from 'vue'
|
||||
import { NButton, NInput, useMessage } from 'naive-ui'
|
||||
import { Message } from './components'
|
||||
import { Layout } from './layout'
|
||||
import { useChat } from './hooks/useChat'
|
||||
import { fetchChatAPI } from '@/api'
|
||||
import { HoverButton, SvgIcon } from '@/components/common'
|
||||
import { useHistoryStore } from '@/store'
|
||||
|
||||
let controller = new AbortController()
|
||||
|
||||
const ms = useMessage()
|
||||
|
||||
const historyStore = useHistoryStore()
|
||||
|
||||
const scrollRef = ref<HTMLDivElement>()
|
||||
|
||||
const { addChat, clearChat } = useChat()
|
||||
|
||||
const prompt = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
const currentActive = computed(() => historyStore.active)
|
||||
const heartbeat = computed(() => historyStore.heartbeat)
|
||||
|
||||
const list = computed<Chat.Chat[]>(() => historyStore.getCurrentChat)
|
||||
const chatList = computed<Chat.Chat[]>(() => list.value.filter(item => (!item.reversal && !item.error)))
|
||||
|
||||
async function handleSubmit() {
|
||||
if (loading.value)
|
||||
return
|
||||
|
||||
controller = new AbortController()
|
||||
|
||||
const message = prompt.value.trim()
|
||||
|
||||
if (!message || !message.length) {
|
||||
ms.warning('Please enter a message')
|
||||
return
|
||||
}
|
||||
|
||||
addMessage(message, { reversal: true })
|
||||
prompt.value = ''
|
||||
|
||||
let options: Chat.ChatOptions = {}
|
||||
const lastContext = chatList.value[chatList.value.length - 1]?.options
|
||||
|
||||
if (lastContext)
|
||||
options = { ...lastContext }
|
||||
|
||||
try {
|
||||
loading.value = true
|
||||
const { data } = await fetchChatAPI(message, options, controller.signal)
|
||||
addMessage(data?.text ?? '', { options: { conversationId: data.conversationId, parentMessageId: data.id } })
|
||||
}
|
||||
catch (error: any) {
|
||||
if (error.message !== 'canceled')
|
||||
addMessage(`${error.message ?? 'Request failed, please try again later.'}`, { error: true })
|
||||
}
|
||||
finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleEnter(event: KeyboardEvent) {
|
||||
if (event.key === 'Enter')
|
||||
handleSubmit()
|
||||
}
|
||||
|
||||
function addMessage(
|
||||
message: string,
|
||||
args?: { reversal?: boolean; error?: boolean; options?: Chat.ChatOptions },
|
||||
) {
|
||||
addChat(message, args)
|
||||
scrollToBottom()
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
nextTick(() => scrollRef.value && (scrollRef.value.scrollTop = scrollRef.value.scrollHeight))
|
||||
}
|
||||
|
||||
function handleClear() {
|
||||
handleCancel()
|
||||
clearChat()
|
||||
}
|
||||
|
||||
function handleCancel() {
|
||||
controller.abort()
|
||||
controller = new AbortController()
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
scrollToBottom()
|
||||
})
|
||||
|
||||
watch(
|
||||
heartbeat,
|
||||
() => {
|
||||
handleCancel()
|
||||
scrollToBottom()
|
||||
},
|
||||
)
|
||||
|
||||
watch(
|
||||
currentActive,
|
||||
(_, oldActive) => {
|
||||
if (oldActive !== null) {
|
||||
handleCancel()
|
||||
scrollToBottom()
|
||||
}
|
||||
},
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Layout>
|
||||
<div class="flex flex-col h-full">
|
||||
<main class="flex-1 overflow-hidden">
|
||||
<div ref="scrollRef" class="h-full p-4 overflow-hidden overflow-y-auto">
|
||||
<div>
|
||||
<Message
|
||||
v-for="(item, index) of list" :key="index" :date-time="item.dateTime" :message="item.message"
|
||||
:reversal="item.reversal" :error="item.error"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="p-4">
|
||||
<div class="flex items-center justify-between space-x-2">
|
||||
<HoverButton tooltip="Clear conversations">
|
||||
<span class="text-xl text-[#4f555e]" @click="handleClear">
|
||||
<SvgIcon icon="ri:delete-bin-line" />
|
||||
</span>
|
||||
</HoverButton>
|
||||
<NInput v-model:value="prompt" placeholder="Type a message..." @keypress="handleEnter" />
|
||||
<NButton type="primary" :loading="loading" @click="handleSubmit">
|
||||
<template #icon>
|
||||
<SvgIcon icon="ri:send-plane-fill" />
|
||||
</template>
|
||||
</NButton>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</Layout>
|
||||
</template>
|
15
src/components/business/Chat/layout/Layout.vue
Normal file
15
src/components/business/Chat/layout/Layout.vue
Normal file
@@ -0,0 +1,15 @@
|
||||
<script setup lang='ts'>
|
||||
import { NLayout, NLayoutContent } from 'naive-ui'
|
||||
import Sider from './sider/index.vue'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="h-full overflow-hidden border rounded-md shadow-md">
|
||||
<NLayout class="h-full" has-sider>
|
||||
<Sider />
|
||||
<NLayoutContent class="h-full">
|
||||
<slot />
|
||||
</NLayoutContent>
|
||||
</NLayout>
|
||||
</div>
|
||||
</template>
|
3
src/components/business/Chat/layout/index.ts
Normal file
3
src/components/business/Chat/layout/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import Layout from './Layout.vue'
|
||||
|
||||
export { Layout }
|
14
src/components/business/Chat/layout/sider/Footer.vue
Normal file
14
src/components/business/Chat/layout/sider/Footer.vue
Normal file
@@ -0,0 +1,14 @@
|
||||
<script setup lang='ts'>
|
||||
import { HoverButton, SvgIcon, UserAvatar } from '@/components/common'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<footer class="flex items-center justify-between min-w-0 p-4 overflow-hidden border-t h-[70px]">
|
||||
<UserAvatar class="flex-1" />
|
||||
<HoverButton tooltip="Setting">
|
||||
<span class="text-xl text-[#4f555e]">
|
||||
<SvgIcon icon="ri:settings-4-line" />
|
||||
</span>
|
||||
</HoverButton>
|
||||
</footer>
|
||||
</template>
|
71
src/components/business/Chat/layout/sider/List.vue
Normal file
71
src/components/business/Chat/layout/sider/List.vue
Normal file
@@ -0,0 +1,71 @@
|
||||
<script setup lang='ts'>
|
||||
import { ref } from 'vue'
|
||||
import { NInput, NScrollbar } from 'naive-ui'
|
||||
import { SvgIcon } from '@/components/common'
|
||||
import { useHistoryStore } from '@/store'
|
||||
|
||||
const historyStore = useHistoryStore()
|
||||
|
||||
const dataSources = ref(historyStore.historyChat)
|
||||
|
||||
function handleSelect(index: number) {
|
||||
historyStore.chooseHistory(index)
|
||||
}
|
||||
|
||||
function handleEdit(index: number, isEdit: boolean, event?: MouseEvent) {
|
||||
historyStore.editHistory(index, isEdit)
|
||||
event?.stopPropagation()
|
||||
}
|
||||
|
||||
function handleRemove(index: number, event?: MouseEvent) {
|
||||
historyStore.removeHistory(index)
|
||||
event?.stopPropagation()
|
||||
}
|
||||
|
||||
function handleEnter(index: number, isEdit: boolean, event: KeyboardEvent) {
|
||||
if (event.key === 'Enter') {
|
||||
handleEdit(index, isEdit)
|
||||
event.stopPropagation()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NScrollbar class="px-4">
|
||||
<div class="flex flex-col gap-2 text-sm">
|
||||
<div v-for="(item, index) of dataSources" :key="index">
|
||||
<a
|
||||
class="relative flex items-center gap-3 px-3 py-3 break-all border rounded-md cursor-pointer hover:bg-neutral-100 group"
|
||||
:class="historyStore.active === index && ['border-[#4b9e5f]', 'bg-neutral-100', 'text-[#4b9e5f]', 'pr-14']"
|
||||
@click="handleSelect(index)"
|
||||
>
|
||||
<span>
|
||||
<SvgIcon icon="ri:message-3-line" />
|
||||
</span>
|
||||
<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"
|
||||
@keypress="handleEnter(index, false, $event)"
|
||||
/>
|
||||
<span v-else>{{ item.title }}</span>
|
||||
</div>
|
||||
<div v-if="historyStore.active === index" class="absolute z-10 flex visible right-1">
|
||||
<template v-if="item.isEdit">
|
||||
<button class="p-1" @click="handleEdit(index, false, $event)">
|
||||
<SvgIcon icon="ri:save-line" />
|
||||
</button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<button class="p-1">
|
||||
<SvgIcon icon="ri:edit-line" @click="handleEdit(index, true, $event)" />
|
||||
</button>
|
||||
<button class="p-1" @click="handleRemove(index, $event)">
|
||||
<SvgIcon icon="ri:delete-bin-line" />
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</NScrollbar>
|
||||
</template>
|
49
src/components/business/Chat/layout/sider/index.vue
Normal file
49
src/components/business/Chat/layout/sider/index.vue
Normal file
@@ -0,0 +1,49 @@
|
||||
<script setup lang='ts'>
|
||||
import { ref } from 'vue'
|
||||
import { NButton, NLayoutSider } from 'naive-ui'
|
||||
import List from './List.vue'
|
||||
import Footer from './Footer.vue'
|
||||
import { useAppStore, useHistoryStore } from '@/store'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const historyStore = useHistoryStore()
|
||||
|
||||
const collapsed = ref(appStore.siderCollapsed ?? false)
|
||||
|
||||
function handleAdd() {
|
||||
historyStore.addHistory({
|
||||
title: 'New Chat',
|
||||
isEdit: false,
|
||||
data: [],
|
||||
})
|
||||
}
|
||||
|
||||
function handleCollapsed() {
|
||||
collapsed.value = !collapsed.value
|
||||
appStore.setSiderCollapsed(collapsed.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NLayoutSider
|
||||
:collapsed="collapsed"
|
||||
:collapsed-width="0"
|
||||
:width="260"
|
||||
collapse-mode="transform"
|
||||
show-trigger="arrow-circle"
|
||||
bordered
|
||||
@update:collapsed="handleCollapsed"
|
||||
>
|
||||
<div class="flex flex-col h-full">
|
||||
<main class="flex-1 min-h-0 overflow-hidden">
|
||||
<div class="p-4">
|
||||
<NButton dashed block @click="handleAdd">
|
||||
New chat
|
||||
</NButton>
|
||||
</div>
|
||||
<List />
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
</NLayoutSider>
|
||||
</template>
|
3
src/components/business/index.ts
Normal file
3
src/components/business/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import Chat from './Chat/index.vue'
|
||||
|
||||
export { Chat }
|
20
src/components/common/HoverButton/Button.vue
Normal file
20
src/components/common/HoverButton/Button.vue
Normal file
@@ -0,0 +1,20 @@
|
||||
<script setup lang='ts'>
|
||||
interface Emit {
|
||||
(e: 'click'): void
|
||||
}
|
||||
|
||||
const emit = defineEmits<Emit>()
|
||||
|
||||
function handleClick() {
|
||||
emit('click')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
class="flex items-center justify-center w-10 h-10 transition rounded-full hover:bg-neutral-100"
|
||||
@click="handleClick"
|
||||
>
|
||||
<slot />
|
||||
</button>
|
||||
</template>
|
46
src/components/common/HoverButton/index.vue
Normal file
46
src/components/common/HoverButton/index.vue
Normal file
@@ -0,0 +1,46 @@
|
||||
<script setup lang='ts'>
|
||||
import { computed } from 'vue'
|
||||
import type { PopoverPlacement } from 'naive-ui'
|
||||
import { NTooltip } from 'naive-ui'
|
||||
import Button from './Button.vue'
|
||||
|
||||
interface Props {
|
||||
tooltip?: string
|
||||
placement?: PopoverPlacement
|
||||
}
|
||||
|
||||
interface Emit {
|
||||
(e: 'click'): void
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
tooltip: '',
|
||||
placement: 'bottom',
|
||||
})
|
||||
|
||||
const emit = defineEmits<Emit>()
|
||||
|
||||
const showTooltip = computed(() => Boolean(props.tooltip))
|
||||
|
||||
function handleClick() {
|
||||
emit('click')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="showTooltip">
|
||||
<NTooltip :placement="placement" trigger="hover">
|
||||
<template #trigger>
|
||||
<Button @click="handleClick">
|
||||
<slot />
|
||||
</Button>
|
||||
</template>
|
||||
{{ tooltip }}
|
||||
</NTooltip>
|
||||
</div>
|
||||
<div v-else>
|
||||
<Button @click="handleClick">
|
||||
<slot />
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
43
src/components/common/NaiveProvider/index.vue
Normal file
43
src/components/common/NaiveProvider/index.vue
Normal file
@@ -0,0 +1,43 @@
|
||||
<script setup lang="ts">
|
||||
import { defineComponent, h } from 'vue'
|
||||
import {
|
||||
NDialogProvider,
|
||||
NLoadingBarProvider,
|
||||
NMessageProvider,
|
||||
NNotificationProvider,
|
||||
useDialog,
|
||||
useLoadingBar,
|
||||
useMessage,
|
||||
useNotification,
|
||||
} from 'naive-ui'
|
||||
|
||||
function registerNaiveTools() {
|
||||
window.$loadingBar = useLoadingBar()
|
||||
window.$dialog = useDialog()
|
||||
window.$message = useMessage()
|
||||
window.$notification = useNotification()
|
||||
}
|
||||
|
||||
const NaiveProviderContent = defineComponent({
|
||||
name: 'NaiveProviderContent',
|
||||
setup() {
|
||||
registerNaiveTools()
|
||||
},
|
||||
render() {
|
||||
return h('div')
|
||||
},
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NLoadingBarProvider>
|
||||
<NDialogProvider>
|
||||
<NNotificationProvider>
|
||||
<NMessageProvider>
|
||||
<slot />
|
||||
<NaiveProviderContent />
|
||||
</NMessageProvider>
|
||||
</NNotificationProvider>
|
||||
</NDialogProvider>
|
||||
</NLoadingBarProvider>
|
||||
</template>
|
23
src/components/common/UserAvatar/index.vue
Normal file
23
src/components/common/UserAvatar/index.vue
Normal file
@@ -0,0 +1,23 @@
|
||||
<script setup lang='ts'>
|
||||
import { GithubSite } from '@/components/custom'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex items-center">
|
||||
<div class="w-10 h-10 overflow-hidden rounded-full">
|
||||
<img class="object-cover" src="@/assets/avatar.jpg" alt="avatar">
|
||||
</div>
|
||||
<div class="ml-2">
|
||||
<h2 class="font-bold text-md">
|
||||
ChenZhaoYu
|
||||
</h2>
|
||||
<p class="text-xs text-gray-500">
|
||||
<GithubSite />
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
|
||||
</style>
|
6
src/components/common/index.ts
Normal file
6
src/components/common/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import HoverButton from './HoverButton/index.vue'
|
||||
import NaiveProvider from './NaiveProvider/index.vue'
|
||||
import SvgIcon from './SvgIcon/index.vue'
|
||||
import UserAvatar from './UserAvatar/index.vue'
|
||||
|
||||
export { HoverButton, NaiveProvider, SvgIcon, UserAvatar }
|
8
src/components/custom/GithubSite.vue
Normal file
8
src/components/custom/GithubSite.vue
Normal file
@@ -0,0 +1,8 @@
|
||||
<template>
|
||||
<div class="text-center text-neutral-500">
|
||||
<span>❤️ Star on</span>
|
||||
<a href="https://github.com/Chanzhaoyu/chatgpt-bot" target="_blank" class="text-blue-500">
|
||||
GitHub
|
||||
</a>
|
||||
</div>
|
||||
</template>
|
3
src/components/custom/index.ts
Normal file
3
src/components/custom/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import GithubSite from './GithubSite.vue'
|
||||
|
||||
export { GithubSite }
|
@@ -1,5 +0,0 @@
|
||||
import NaiveProvider from './NaiveProvider.vue'
|
||||
import Icon from './Icon.vue'
|
||||
import GithubSite from './GithubSite.vue'
|
||||
|
||||
export { NaiveProvider, Icon, GithubSite }
|
15
src/directives/highlight.ts
Normal file
15
src/directives/highlight.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { App, Directive } from 'vue'
|
||||
import hljs from 'highlight.js'
|
||||
|
||||
const regexp = /^(?:\s{4}|\t).+/gm
|
||||
|
||||
export default function setupHighlightDirective(app: App) {
|
||||
const highLightDirective: Directive<HTMLElement> = {
|
||||
mounted(el: HTMLElement) {
|
||||
if (el.textContent?.indexOf(' = ') !== -1 || el.textContent.match(regexp))
|
||||
hljs.highlightBlock(el)
|
||||
},
|
||||
}
|
||||
|
||||
app.directive('highlight', highLightDirective)
|
||||
}
|
6
src/directives/index.ts
Normal file
6
src/directives/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import type { App } from 'vue'
|
||||
import setupHighlightDirective from './highlight'
|
||||
|
||||
export function setupDirectives(app: App) {
|
||||
setupHighlightDirective(app)
|
||||
}
|
24
src/main.ts
24
src/main.ts
@@ -1,18 +1,20 @@
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import './styles/global.css'
|
||||
import { setupDirectives } from './directives'
|
||||
import { setupAssets } from '@/plugins'
|
||||
import { setupStore } from '@/store'
|
||||
import { setupRouter } from '@/router'
|
||||
|
||||
/** Tailwind's Preflight Style Override */
|
||||
function naiveStyleOverride() {
|
||||
const meta = document.createElement('meta')
|
||||
meta.name = 'naive-ui-style'
|
||||
document.head.appendChild(meta)
|
||||
}
|
||||
|
||||
/** Setup */
|
||||
function bootstrap() {
|
||||
async function bootstrap() {
|
||||
const app = createApp(App)
|
||||
naiveStyleOverride()
|
||||
setupAssets()
|
||||
|
||||
setupStore(app)
|
||||
|
||||
setupDirectives(app)
|
||||
|
||||
await setupRouter(app)
|
||||
|
||||
app.mount('#app')
|
||||
}
|
||||
|
||||
|
15
src/plugins/assets.ts
Normal file
15
src/plugins/assets.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import 'highlight.js/styles/xcode.css'
|
||||
import '@/styles/global.css'
|
||||
|
||||
/** Tailwind's Preflight Style Override */
|
||||
function naiveStyleOverride() {
|
||||
const meta = document.createElement('meta')
|
||||
meta.name = 'naive-ui-style'
|
||||
document.head.appendChild(meta)
|
||||
}
|
||||
|
||||
function setupAssets() {
|
||||
naiveStyleOverride()
|
||||
}
|
||||
|
||||
export default setupAssets
|
3
src/plugins/index.ts
Normal file
3
src/plugins/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import setupAssets from './assets'
|
||||
|
||||
export { setupAssets }
|
22
src/router/index.ts
Normal file
22
src/router/index.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import type { App } from 'vue'
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/',
|
||||
name: 'Home',
|
||||
component: () => import('@/views/home/index.vue'),
|
||||
},
|
||||
]
|
||||
|
||||
export const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes,
|
||||
scrollBehavior: () => ({ left: 0, top: 0 }),
|
||||
})
|
||||
|
||||
export async function setupRouter(app: App) {
|
||||
app.use(router)
|
||||
await router.isReady()
|
||||
}
|
9
src/store/index.ts
Normal file
9
src/store/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { App } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
|
||||
export function setupStore(app: App) {
|
||||
const store = createPinia()
|
||||
app.use(store)
|
||||
}
|
||||
|
||||
export * from './modules'
|
20
src/store/modules/app/helper.ts
Normal file
20
src/store/modules/app/helper.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { ss } from '@/utils/storage'
|
||||
|
||||
const LOCAL_NAME = 'appSetting'
|
||||
|
||||
export interface AppState {
|
||||
siderCollapsed: boolean
|
||||
}
|
||||
|
||||
export function defaultSetting() {
|
||||
return { siderCollapsed: false }
|
||||
}
|
||||
|
||||
export function getLocalSetting() {
|
||||
const localSetting: AppState | undefined = ss.get(LOCAL_NAME)
|
||||
return localSetting ?? defaultSetting()
|
||||
}
|
||||
|
||||
export function setLocalSetting(setting: AppState) {
|
||||
ss.set(LOCAL_NAME, setting)
|
||||
}
|
13
src/store/modules/app/index.ts
Normal file
13
src/store/modules/app/index.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { AppState } from './helper'
|
||||
import { getLocalSetting, setLocalSetting } from './helper'
|
||||
|
||||
export const useAppStore = defineStore('app-store', {
|
||||
state: (): AppState => getLocalSetting(),
|
||||
actions: {
|
||||
setSiderCollapsed(collapsed: boolean) {
|
||||
this.siderCollapsed = collapsed
|
||||
setLocalSetting(this.$state)
|
||||
},
|
||||
},
|
||||
})
|
22
src/store/modules/history/helper.ts
Normal file
22
src/store/modules/history/helper.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { ss } from '@/utils/storage'
|
||||
|
||||
const LOCAL_NAME = 'historyChat'
|
||||
|
||||
export interface HistoryState {
|
||||
historyChat: Chat.HistoryChat[]
|
||||
active: number | null
|
||||
heartbeat: boolean
|
||||
}
|
||||
|
||||
export function defaultSetting() {
|
||||
return { historyChat: [], active: null, heartbeat: false }
|
||||
}
|
||||
|
||||
export function getLocalHistory() {
|
||||
const localSetting: HistoryState | undefined = ss.get(LOCAL_NAME)
|
||||
return localSetting ?? defaultSetting()
|
||||
}
|
||||
|
||||
export function setLocalHistory(data: HistoryState) {
|
||||
ss.set(LOCAL_NAME, data)
|
||||
}
|
83
src/store/modules/history/index.ts
Normal file
83
src/store/modules/history/index.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { HistoryState } from './helper'
|
||||
import { getLocalHistory, setLocalHistory } from './helper'
|
||||
|
||||
export const useHistoryStore = defineStore('history-store', {
|
||||
state: (): HistoryState => getLocalHistory(),
|
||||
getters: {
|
||||
getCurrentHistory(state): Chat.HistoryChat {
|
||||
if (state.historyChat.length) {
|
||||
if (state.active === null || state.active >= state.historyChat.length || state.active < 0)
|
||||
state.active = 0
|
||||
return state.historyChat[state.active] ?? { title: '', isEdit: false, data: [] }
|
||||
}
|
||||
state.active = null
|
||||
return { title: '', isEdit: false, data: [] }
|
||||
},
|
||||
getCurrentChat(): Chat.Chat[] {
|
||||
return this.getCurrentHistory.data ?? []
|
||||
},
|
||||
},
|
||||
actions: {
|
||||
addChat(data: Chat.Chat) {
|
||||
if (this.active === null) {
|
||||
this.historyChat.push({ title: data.message, isEdit: false, data: [data] })
|
||||
this.active = this.historyChat.length - 1
|
||||
}
|
||||
else {
|
||||
if (this.historyChat[this.active].title === 'New Chat')
|
||||
this.historyChat[this.active].title = data.message
|
||||
|
||||
this.historyChat[this.active].data.push(data)
|
||||
}
|
||||
setLocalHistory(this.$state)
|
||||
},
|
||||
|
||||
clearChat() {
|
||||
if (this.active !== null) {
|
||||
this.historyChat[this.active].data = []
|
||||
setLocalHistory(this.$state)
|
||||
}
|
||||
},
|
||||
|
||||
addHistory(data: Chat.HistoryChat) {
|
||||
this.historyChat.push(data)
|
||||
this.active = this.historyChat.length - 1
|
||||
setLocalHistory(this.$state)
|
||||
},
|
||||
|
||||
editHistory(index: number, isEdit: boolean) {
|
||||
this.historyChat[index].isEdit = isEdit
|
||||
setLocalHistory(this.$state)
|
||||
},
|
||||
|
||||
removeHistory(index: number) {
|
||||
this.historyChat.splice(index, 1)
|
||||
|
||||
if (this.active === index) {
|
||||
if (this.historyChat.length === 0)
|
||||
this.active = null
|
||||
else if (this.active === this.historyChat.length)
|
||||
this.active = this.historyChat.length - 1
|
||||
}
|
||||
|
||||
if (this.historyChat.length === 0)
|
||||
this.active = null
|
||||
|
||||
this.toggleHeartbeat()
|
||||
|
||||
setLocalHistory(this.$state)
|
||||
},
|
||||
|
||||
chooseHistory(index: number) {
|
||||
if (this.active === index)
|
||||
return
|
||||
this.active = index
|
||||
setLocalHistory(this.$state)
|
||||
},
|
||||
|
||||
toggleHeartbeat() {
|
||||
this.heartbeat = !this.heartbeat
|
||||
},
|
||||
},
|
||||
})
|
2
src/store/modules/index.ts
Normal file
2
src/store/modules/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './app'
|
||||
export * from './history'
|
20
src/typings/chat.d.ts
vendored
Normal file
20
src/typings/chat.d.ts
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
declare namespace Chat{
|
||||
interface ChatOptions {
|
||||
conversationId?: string
|
||||
parentMessageId?: string
|
||||
}
|
||||
|
||||
interface Chat {
|
||||
dateTime: string
|
||||
message: string
|
||||
reversal?: boolean
|
||||
error?: boolean
|
||||
options?: ChatOptions
|
||||
}
|
||||
|
||||
interface HistoryChat {
|
||||
title: string
|
||||
isEdit: boolean
|
||||
data: Chat[]
|
||||
}
|
||||
}
|
2
src/typings/env.d.ts
vendored
2
src/typings/env.d.ts
vendored
@@ -1,6 +1,6 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
/** api url */
|
||||
readonly VITE_GLOB_API_URL: string;
|
||||
readonly VITE_APP_API_BASE_URL: string;
|
||||
}
|
||||
|
3
src/typings/global.d.ts
vendored
3
src/typings/global.d.ts
vendored
@@ -1,3 +1,6 @@
|
||||
interface Window {
|
||||
$loadingBar?: import('naive-ui').LoadingBarProviderInst;
|
||||
$dialog?: import('naive-ui').DialogProviderInst;
|
||||
$message?: import('naive-ui').MessageProviderInst;
|
||||
$notification?: import('naive-ui').NotificationProviderInst;
|
||||
}
|
||||
|
18
src/utils/crypto/index.ts
Normal file
18
src/utils/crypto/index.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import CryptoJS from 'crypto-js'
|
||||
|
||||
const CryptoSecret = '__CRYPTO_SECRET__'
|
||||
|
||||
export function enCrypto(data: any) {
|
||||
const str = JSON.stringify(data)
|
||||
return CryptoJS.AES.encrypt(str, CryptoSecret).toString()
|
||||
}
|
||||
|
||||
export function deCrypto(data: string) {
|
||||
const bytes = CryptoJS.AES.decrypt(data, CryptoSecret)
|
||||
const str = bytes.toString(CryptoJS.enc.Utf8)
|
||||
|
||||
if (str)
|
||||
return JSON.parse(str)
|
||||
|
||||
return null
|
||||
}
|
55
src/utils/is/index.ts
Normal file
55
src/utils/is/index.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
export function isNumber<T extends number>(value: T | unknown): value is number {
|
||||
return Object.prototype.toString.call(value) === '[object Number]'
|
||||
}
|
||||
|
||||
export function isString<T extends string>(value: T | unknown): value is string {
|
||||
return Object.prototype.toString.call(value) === '[object String]'
|
||||
}
|
||||
|
||||
export function isBoolean<T extends boolean>(value: T | unknown): value is boolean {
|
||||
return Object.prototype.toString.call(value) === '[object Boolean]'
|
||||
}
|
||||
|
||||
export function isNull<T extends null>(value: T | unknown): value is null {
|
||||
return Object.prototype.toString.call(value) === '[object Null]'
|
||||
}
|
||||
|
||||
export function isUndefined<T extends undefined>(value: T | unknown): value is undefined {
|
||||
return Object.prototype.toString.call(value) === '[object Undefined]'
|
||||
}
|
||||
|
||||
export function isObject<T extends object>(value: T | unknown): value is object {
|
||||
return Object.prototype.toString.call(value) === '[object Object]'
|
||||
}
|
||||
|
||||
export function isArray<T extends any[]>(value: T | unknown): value is T {
|
||||
return Object.prototype.toString.call(value) === '[object Array]'
|
||||
}
|
||||
|
||||
export function isFunction<T extends (...args: any[]) => any | void | never>(value: T | unknown): value is T {
|
||||
return Object.prototype.toString.call(value) === '[object Function]'
|
||||
}
|
||||
|
||||
export function isDate<T extends Date>(value: T | unknown): value is T {
|
||||
return Object.prototype.toString.call(value) === '[object Date]'
|
||||
}
|
||||
|
||||
export function isRegExp<T extends RegExp>(value: T | unknown): value is T {
|
||||
return Object.prototype.toString.call(value) === '[object RegExp]'
|
||||
}
|
||||
|
||||
export function isPromise<T extends Promise<any>>(value: T | unknown): value is T {
|
||||
return Object.prototype.toString.call(value) === '[object Promise]'
|
||||
}
|
||||
|
||||
export function isSet<T extends Set<any>>(value: T | unknown): value is T {
|
||||
return Object.prototype.toString.call(value) === '[object Set]'
|
||||
}
|
||||
|
||||
export function isMap<T extends Map<any, any>>(value: T | unknown): value is T {
|
||||
return Object.prototype.toString.call(value) === '[object Map]'
|
||||
}
|
||||
|
||||
export function isFile<T extends File>(value: T | unknown): value is T {
|
||||
return Object.prototype.toString.call(value) === '[object File]'
|
||||
}
|
29
src/utils/request/axios.ts
Normal file
29
src/utils/request/axios.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import axios, { type AxiosResponse } from 'axios'
|
||||
|
||||
const service = axios.create({
|
||||
baseURL: import.meta.env.VITE_GLOB_API_URL,
|
||||
timeout: 30 * 1000,
|
||||
})
|
||||
|
||||
service.interceptors.request.use(
|
||||
(config) => {
|
||||
return config
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error.response)
|
||||
},
|
||||
)
|
||||
|
||||
service.interceptors.response.use(
|
||||
(response: AxiosResponse): AxiosResponse => {
|
||||
if (response.status === 200)
|
||||
return response
|
||||
|
||||
throw new Error(response.status.toString())
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error)
|
||||
},
|
||||
)
|
||||
|
||||
export default service
|
71
src/utils/request/index.ts
Normal file
71
src/utils/request/index.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import type { AxiosResponse, GenericAbortSignal } from 'axios'
|
||||
import request from './axios'
|
||||
|
||||
export interface HttpOption {
|
||||
url: string
|
||||
data?: any
|
||||
method?: string
|
||||
headers?: any
|
||||
signal?: GenericAbortSignal
|
||||
beforeRequest?: () => void
|
||||
afterRequest?: () => void
|
||||
}
|
||||
|
||||
export interface Response<T = any> {
|
||||
data: T
|
||||
message: string | null
|
||||
status: string
|
||||
}
|
||||
|
||||
function http<T = any>({ url, data, method, headers, signal, beforeRequest, afterRequest }: HttpOption) {
|
||||
const successHandler = (res: AxiosResponse<Response<T>>) => {
|
||||
if (res.data.status === 'Success')
|
||||
return res.data
|
||||
|
||||
return Promise.reject(res.data)
|
||||
}
|
||||
|
||||
const failHandler = (error: Response<Error>) => {
|
||||
afterRequest?.()
|
||||
throw new Error(error?.message || 'Error')
|
||||
}
|
||||
|
||||
beforeRequest?.()
|
||||
|
||||
method = method || 'GET'
|
||||
|
||||
const params = Object.assign(typeof data === 'function' ? data() : data ?? {}, {})
|
||||
|
||||
return method === 'GET'
|
||||
? request.get(url, { params, signal }).then(successHandler, failHandler)
|
||||
: request.post(url, params, { headers, signal }).then(successHandler, failHandler)
|
||||
}
|
||||
|
||||
export function get<T = any>(
|
||||
{ url, data, method = 'GET', signal, beforeRequest, afterRequest }: HttpOption,
|
||||
): Promise<Response<T>> {
|
||||
return http<T>({
|
||||
url,
|
||||
method,
|
||||
data,
|
||||
signal,
|
||||
beforeRequest,
|
||||
afterRequest,
|
||||
})
|
||||
}
|
||||
|
||||
export function post<T = any>(
|
||||
{ url, data, method = 'POST', headers, signal, beforeRequest, afterRequest }: HttpOption,
|
||||
): Promise<Response<T>> {
|
||||
return http<T>({
|
||||
url,
|
||||
method,
|
||||
data,
|
||||
headers,
|
||||
signal,
|
||||
beforeRequest,
|
||||
afterRequest,
|
||||
})
|
||||
}
|
||||
|
||||
export default post
|
1
src/utils/storage/index.ts
Normal file
1
src/utils/storage/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './local'
|
70
src/utils/storage/local.ts
Normal file
70
src/utils/storage/local.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { deCrypto, enCrypto } from '../crypto'
|
||||
|
||||
interface StorageData<T = any> {
|
||||
data: T
|
||||
expire: number | null
|
||||
}
|
||||
|
||||
export function createLocalStorage(options?: { expire?: number | null; crypto?: boolean }) {
|
||||
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7
|
||||
|
||||
const { expire, crypto } = Object.assign(
|
||||
{
|
||||
expire: DEFAULT_CACHE_TIME,
|
||||
crypto: true,
|
||||
},
|
||||
options,
|
||||
)
|
||||
|
||||
function set<T = any>(key: string, data: T) {
|
||||
const storageData: StorageData<T> = {
|
||||
data,
|
||||
expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
|
||||
}
|
||||
|
||||
const json = crypto ? enCrypto(storageData) : JSON.stringify(storageData)
|
||||
window.localStorage.setItem(key, json)
|
||||
}
|
||||
|
||||
function get(key: string) {
|
||||
const json = window.localStorage.getItem(key)
|
||||
if (json) {
|
||||
let storageData: StorageData | null = null
|
||||
|
||||
try {
|
||||
storageData = crypto ? deCrypto(json) : JSON.parse(json)
|
||||
}
|
||||
catch {
|
||||
// Prevent failure
|
||||
}
|
||||
|
||||
if (storageData) {
|
||||
const { data, expire } = storageData
|
||||
if (expire === null || expire >= Date.now())
|
||||
return data
|
||||
}
|
||||
|
||||
remove(key)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function remove(key: string) {
|
||||
window.localStorage.removeItem(key)
|
||||
}
|
||||
|
||||
function clear() {
|
||||
window.localStorage.clear()
|
||||
}
|
||||
|
||||
return {
|
||||
set,
|
||||
get,
|
||||
remove,
|
||||
clear,
|
||||
}
|
||||
}
|
||||
|
||||
export const ls = createLocalStorage()
|
||||
|
||||
export const ss = createLocalStorage({ expire: null, crypto: false })
|
@@ -1,34 +0,0 @@
|
||||
<script setup lang='ts'>
|
||||
import { Icon } from '@/components'
|
||||
|
||||
interface Props {
|
||||
user?: boolean
|
||||
date?: string
|
||||
message?: string
|
||||
error?: boolean
|
||||
}
|
||||
|
||||
defineProps<Props>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex w-full mb-6" :class="[{ 'flex-row-reverse': user }]">
|
||||
<div
|
||||
class="flex items-center justify-center rounded-full overflow-hidden w-[32px] h-[32px]"
|
||||
:class="[user ? 'ml-3' : 'mr-3']"
|
||||
>
|
||||
<img v-if="user" src="@/assets/avatar.jpg" class="object-cover w-full h-full " alt="avatar">
|
||||
<Icon v-else local-icon="logo" class="text-[26px]" />
|
||||
</div>
|
||||
<div class="flex flex-col flex-1 text-sm" :class="[{ 'items-end': user }]">
|
||||
<span class="text-xs text-[#b4bbc4]">
|
||||
{{ date }}
|
||||
</span>
|
||||
<div class="p-2 mt-2 rounded-md" :class="[user ? 'bg-[#d2f9d1]' : 'bg-[#f4f6f8]']">
|
||||
<span class="leading-relaxed whitespace-pre" :class="[{ 'text-red-500': error }]">
|
||||
{{ message }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
@@ -1,5 +0,0 @@
|
||||
<template>
|
||||
<span class="leading-relaxed whitespace-pre-wrap">
|
||||
<slot />
|
||||
</span>
|
||||
</template>
|
@@ -1,109 +0,0 @@
|
||||
<script setup lang='ts'>
|
||||
import { nextTick, onMounted, ref } from 'vue'
|
||||
import { NButton, NInput, NPopover, useMessage } from 'naive-ui'
|
||||
import { Message } from './components'
|
||||
import { fetchChatAPI } from './request'
|
||||
import { Icon } from '@/components'
|
||||
|
||||
interface ListProps {
|
||||
dateTime: string
|
||||
message: string
|
||||
reversal?: boolean
|
||||
}
|
||||
|
||||
const scrollRef = ref<HTMLDivElement>()
|
||||
|
||||
const ms = useMessage()
|
||||
|
||||
const value = ref('')
|
||||
|
||||
const loading = ref(false)
|
||||
|
||||
const list = ref<ListProps[]>([])
|
||||
|
||||
onMounted(initChat)
|
||||
|
||||
function initChat() {
|
||||
addMessage('Hi, I am ChatGPT, a chatbot based on GPT-3.', false)
|
||||
}
|
||||
|
||||
function handleClear() {
|
||||
list.value = []
|
||||
setTimeout(initChat, 100)
|
||||
}
|
||||
|
||||
function handleEnter(event: KeyboardEvent) {
|
||||
if (event.key === 'Enter')
|
||||
handleSubmit()
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!value.value) {
|
||||
ms.warning('Please enter a message')
|
||||
return
|
||||
}
|
||||
|
||||
addMessage(value.value, true)
|
||||
|
||||
try {
|
||||
loading.value = true
|
||||
const { text } = await fetchChatAPI(value.value)
|
||||
value.value = ''
|
||||
addMessage(text, false)
|
||||
}
|
||||
catch (error: any) {
|
||||
addMessage(error.message ?? 'Request failed, please try again later.', false)
|
||||
}
|
||||
finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function addMessage(message: string, reversal = false) {
|
||||
list.value.push({ dateTime: new Date().toLocaleString(), message, reversal })
|
||||
nextTick(() => scrollRef.value && (scrollRef.value.scrollTop = scrollRef.value.scrollHeight))
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col h-full overflow-hidden border rounded-md shadow-md">
|
||||
<header class="flex items-center justify-between p-4">
|
||||
<h1 class="text-xl font-bold">
|
||||
ChatGPT Web
|
||||
</h1>
|
||||
<div>
|
||||
<NPopover>
|
||||
<template #trigger>
|
||||
<button
|
||||
class="w-[40px] h-[40px] rounded-full hover:bg-neutral-100 transition flex justify-center items-center"
|
||||
@click="handleClear"
|
||||
>
|
||||
<Icon icon="ri:delete-bin-6-line" />
|
||||
</button>
|
||||
</template>
|
||||
<span>Clear</span>
|
||||
</NPopover>
|
||||
</div>
|
||||
</header>
|
||||
<main class="flex-1 overflow-hidden border-y">
|
||||
<div ref="scrollRef" class="h-full p-4 overflow-hidden overflow-y-auto">
|
||||
<div>
|
||||
<Message
|
||||
v-for="(item, index) of list" :key="index" :date-time="item.dateTime" :message="item.message"
|
||||
:reversal="item.reversal"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="p-4">
|
||||
<div class="flex items-center justify-between space-x-2">
|
||||
<NInput v-model:value="value" :disabled="loading" placeholder="Type a message..." @keyup="handleEnter" />
|
||||
<NButton type="primary" :loading="loading" @click="handleSubmit">
|
||||
<template #icon>
|
||||
<Icon icon="ri:send-plane-fill" />
|
||||
</template>
|
||||
</NButton>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</template>
|
@@ -1,27 +0,0 @@
|
||||
import axios from 'axios'
|
||||
|
||||
async function fetchChatAPI(message: string) {
|
||||
const url = `${import.meta.env.VITE_GLOB_API_URL}/chat`
|
||||
|
||||
if (!message || message.trim() === '')
|
||||
return
|
||||
|
||||
try {
|
||||
const { status, data } = await axios.post(url, { message })
|
||||
|
||||
if (status === 200) {
|
||||
if (data.text)
|
||||
return Promise.resolve(data)
|
||||
|
||||
if (data.statusText)
|
||||
return Promise.reject(new Error(data.statusText))
|
||||
}
|
||||
|
||||
return Promise.reject(new Error('Request failed'))
|
||||
}
|
||||
catch (error) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
export { fetchChatAPI }
|
9
src/views/home/index.vue
Normal file
9
src/views/home/index.vue
Normal file
@@ -0,0 +1,9 @@
|
||||
<script setup lang='ts'>
|
||||
import { Chat } from '@/components/business'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="h-full p-4 overflow-hidden">
|
||||
<Chat />
|
||||
</div>
|
||||
</template>
|
@@ -1,22 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"module": "ESNext",
|
||||
"target": "ESNext",
|
||||
"lib": ["DOM", "ESNext"],
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"jsx": "preserve",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"noUnusedLocals": true,
|
||||
"strictNullChecks": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
"types": ["vite/client", "node", "naive-ui/volar"]
|
||||
},
|
||||
"exclude": ["node_modules", "dist"]
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"module": "ESNext",
|
||||
"target": "ESNext",
|
||||
"lib": ["DOM", "ESNext"],
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"jsx": "preserve",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"noUnusedLocals": true,
|
||||
"strictNullChecks": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
"types": ["vite/client", "node", "naive-ui/volar"]
|
||||
},
|
||||
"exclude": ["node_modules", "dist", "service"]
|
||||
}
|
||||
|
@@ -1,8 +1,10 @@
|
||||
import path from 'path'
|
||||
import { defineConfig } from 'vite'
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
export default defineConfig(() => {
|
||||
export default defineConfig((env) => {
|
||||
const viteEnv = loadEnv(env.mode, process.cwd()) as unknown as ImportMetaEnv
|
||||
|
||||
return {
|
||||
resolve: {
|
||||
alias: {
|
||||
@@ -14,6 +16,13 @@ export default defineConfig(() => {
|
||||
port: 1002,
|
||||
host: '0.0.0.0',
|
||||
open: false,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: viteEnv.VITE_APP_API_BASE_URL,
|
||||
changeOrigin: true, // 允许跨域
|
||||
rewrite: path => path.replace('/api/', '/'),
|
||||
},
|
||||
},
|
||||
},
|
||||
build: {
|
||||
reportCompressedSize: false,
|
||||
|
Reference in New Issue
Block a user