From a6c598c0172ee0121b92e7a114c7145846614006 Mon Sep 17 00:00:00 2001 From: Dakai Date: Sun, 2 Apr 2023 14:05:05 +0000 Subject: [PATCH] Initial commit Created from https://vercel.com/new --- .eslintignore | 1 + .eslintrc.json | 4 + .gitignore | 39 + .gitpod.yml | 11 + .husky/pre-commit | 4 + .lintstagedrc.json | 6 + .prettierrc.js | 10 + .vscode/settings.json | 4 + Dockerfile | 40 + LICENSE | 75 + README.md | 204 ++ app/api/access.ts | 17 + app/api/chat-stream/route.ts | 52 + app/api/common.ts | 22 + app/api/openai/route.ts | 30 + app/api/openai/typing.ts | 7 + app/components/button.module.scss | 60 + app/components/button.tsx | 28 + app/components/home.module.scss | 452 +++ app/components/home.tsx | 711 ++++ app/components/markdown.tsx | 42 + app/components/settings.module.scss | 20 + app/components/settings.tsx | 498 +++ app/components/ui-lib.module.scss | 160 + app/components/ui-lib.tsx | 142 + app/components/window.scss | 35 + app/constant.ts | 6 + app/icons/add.svg | 23 + app/icons/bot.svg | 28 + app/icons/brain.svg | 25 + app/icons/chat.svg | 27 + app/icons/chatgpt.svg | 16 + app/icons/clear.svg | 1 + app/icons/close.svg | 21 + app/icons/copy.svg | 1 + app/icons/delete.svg | 12 + app/icons/download.svg | 1 + app/icons/edit.svg | 1 + app/icons/export.svg | 1 + app/icons/github.svg | 29 + app/icons/menu.svg | 25 + app/icons/reload.svg | 24 + app/icons/send-white.svg | 21 + app/icons/settings.svg | 21 + app/icons/three-dots.svg | 33 + app/icons/user.svg | 34 + app/layout.tsx | 69 + app/locales/cn.ts | 153 + app/locales/en.ts | 155 + app/locales/es.ts | 157 + app/locales/index.ts | 60 + app/locales/tw.ts | 150 + app/page.tsx | 11 + app/requests.ts | 217 ++ app/store/access.ts | 36 + app/store/app.ts | 505 +++ app/store/index.ts | 3 + app/store/prompt.ts | 117 + app/store/update.ts | 50 + app/styles/globals.scss | 257 ++ app/styles/markdown.scss | 1119 ++++++ app/styles/prism.scss | 122 + app/utils.ts | 79 + middleware.ts | 57 + next.config.js | 21 + package.json | 53 + public/android-chrome-192x192.png | Bin 0 -> 12683 bytes public/android-chrome-512x512.png | Bin 0 -> 24236 bytes public/apple-touch-icon.png | Bin 0 -> 11573 bytes public/favicon-16x16.png | Bin 0 -> 633 bytes public/favicon-32x32.png | Bin 0 -> 1546 bytes public/favicon.ico | Bin 0 -> 15406 bytes public/robots.txt | 4 + public/serviceWorker.js | 13 + public/serviceWorkerRegister.js | 9 + public/site.webmanifest | 21 + scripts/fetch-prompts.mjs | 53 + scripts/setup.sh | 64 + static/cover.png | Bin 0 -> 239154 bytes static/icon.svg | 28 + static/more.png | Bin 0 -> 223481 bytes static/settings.png | Bin 0 -> 90511 bytes tsconfig.json | 28 + yarn.lock | 5204 +++++++++++++++++++++++++++ 84 files changed, 11839 insertions(+) create mode 100644 .eslintignore create mode 100644 .eslintrc.json create mode 100644 .gitignore create mode 100644 .gitpod.yml create mode 100755 .husky/pre-commit create mode 100644 .lintstagedrc.json create mode 100644 .prettierrc.js create mode 100644 .vscode/settings.json create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 README.md create mode 100644 app/api/access.ts create mode 100644 app/api/chat-stream/route.ts create mode 100644 app/api/common.ts create mode 100644 app/api/openai/route.ts create mode 100644 app/api/openai/typing.ts create mode 100644 app/components/button.module.scss create mode 100644 app/components/button.tsx create mode 100644 app/components/home.module.scss create mode 100644 app/components/home.tsx create mode 100644 app/components/markdown.tsx create mode 100644 app/components/settings.module.scss create mode 100644 app/components/settings.tsx create mode 100644 app/components/ui-lib.module.scss create mode 100644 app/components/ui-lib.tsx create mode 100644 app/components/window.scss create mode 100644 app/constant.ts create mode 100644 app/icons/add.svg create mode 100644 app/icons/bot.svg create mode 100644 app/icons/brain.svg create mode 100644 app/icons/chat.svg create mode 100644 app/icons/chatgpt.svg create mode 100644 app/icons/clear.svg create mode 100644 app/icons/close.svg create mode 100644 app/icons/copy.svg create mode 100644 app/icons/delete.svg create mode 100644 app/icons/download.svg create mode 100644 app/icons/edit.svg create mode 100644 app/icons/export.svg create mode 100644 app/icons/github.svg create mode 100644 app/icons/menu.svg create mode 100644 app/icons/reload.svg create mode 100644 app/icons/send-white.svg create mode 100644 app/icons/settings.svg create mode 100644 app/icons/three-dots.svg create mode 100644 app/icons/user.svg create mode 100644 app/layout.tsx create mode 100644 app/locales/cn.ts create mode 100644 app/locales/en.ts create mode 100644 app/locales/es.ts create mode 100644 app/locales/index.ts create mode 100644 app/locales/tw.ts create mode 100644 app/page.tsx create mode 100644 app/requests.ts create mode 100644 app/store/access.ts create mode 100644 app/store/app.ts create mode 100644 app/store/index.ts create mode 100644 app/store/prompt.ts create mode 100644 app/store/update.ts create mode 100644 app/styles/globals.scss create mode 100644 app/styles/markdown.scss create mode 100644 app/styles/prism.scss create mode 100644 app/utils.ts create mode 100644 middleware.ts create mode 100644 next.config.js create mode 100644 package.json create mode 100644 public/android-chrome-192x192.png create mode 100644 public/android-chrome-512x512.png create mode 100644 public/apple-touch-icon.png create mode 100644 public/favicon-16x16.png create mode 100644 public/favicon-32x32.png create mode 100644 public/favicon.ico create mode 100644 public/robots.txt create mode 100644 public/serviceWorker.js create mode 100644 public/serviceWorkerRegister.js create mode 100644 public/site.webmanifest create mode 100644 scripts/fetch-prompts.mjs create mode 100644 scripts/setup.sh create mode 100644 static/cover.png create mode 100644 static/icon.svg create mode 100644 static/more.png create mode 100644 static/settings.png create mode 100644 tsconfig.json create mode 100644 yarn.lock diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000..089752554 --- /dev/null +++ b/.eslintignore @@ -0,0 +1 @@ +public/serviceWorker.js \ No newline at end of file diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 000000000..d229e86f2 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,4 @@ +{ + "extends": "next/core-web-vitals", + "plugins": ["prettier"] +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..0a3e52afa --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts +dev + +public/prompts.json \ No newline at end of file diff --git a/.gitpod.yml b/.gitpod.yml new file mode 100644 index 000000000..d81f2dab1 --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,11 @@ +# This configuration file was automatically generated by Gitpod. +# Please adjust to your needs (see https://www.gitpod.io/docs/introduction/learn-gitpod/gitpod-yaml) +# and commit this file to your remote git repository to share the goodness with others. + +# Learn more from ready-to-use templates: https://www.gitpod.io/docs/introduction/getting-started/quickstart + +tasks: + - init: yarn install && yarn run dev + command: yarn run dev + + diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 000000000..0312b7602 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,4 @@ +#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" + +npx lint-staged \ No newline at end of file diff --git a/.lintstagedrc.json b/.lintstagedrc.json new file mode 100644 index 000000000..58784bad8 --- /dev/null +++ b/.lintstagedrc.json @@ -0,0 +1,6 @@ +{ + "./app/**/*.{js,ts,jsx,tsx,json,html,css,md}": [ + "eslint --fix", + "prettier --write" + ] +} diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 000000000..95cc75ffa --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,10 @@ +module.exports = { + printWidth: 80, + tabWidth: 2, + useTabs: false, + semi: true, + singleQuote: false, + trailingComma: 'all', + bracketSpacing: true, + arrowParens: 'always', +}; diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..bd3337f97 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "typescript.tsdk": "node_modules\\typescript\\lib", + "typescript.enablePromptUseWorkspaceTsdk": true +} \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..6f7547b21 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,40 @@ +FROM node:18-alpine AS base + +FROM base AS deps + +RUN apk add --no-cache libc6-compat + +WORKDIR /app + +COPY package.json yarn.lock ./ + +RUN yarn install + +FROM base AS builder + +RUN apk update && apk add --no-cache git + +ENV OPENAI_API_KEY="" +ENV CODE="" +ARG DOCKER=true + +WORKDIR /app +COPY --from=deps /app/node_modules ./node_modules +COPY . . + +RUN yarn build + +FROM base AS runner +WORKDIR /app + +ENV OPENAI_API_KEY="" +ENV CODE="" + +COPY --from=builder /app/public ./public +COPY --from=builder /app/.next/standalone ./ +COPY --from=builder /app/.next/static ./.next/static +COPY --from=builder /app/.next/server ./.next/server + +EXPOSE 3000 + +CMD ["node","server.js"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..4f00efc87 --- /dev/null +++ b/LICENSE @@ -0,0 +1,75 @@ +版权所有(c)<2023> + +反996许可证版本1.0 + +在符合下列条件的情况下, +特此免费向任何得到本授权作品的副本(包括源代码、文件和/或相关内容,以下统称为“授权作品” +)的个人和法人实体授权:被授权个人或法人实体有权以任何目的处置授权作品,包括但不限于使 +用、复制,修改,衍生利用、散布,发布和再许可: + + +1. 个人或法人实体必须在许可作品的每个再散布或衍生副本上包含以上版权声明和本许可证,不 + 得自行修改。 +2. 个人或法人实体必须严格遵守与个人实际所在地或个人出生地或归化地、或法人实体注册地或 + 经营地(以较严格者为准)的司法管辖区所有适用的与劳动和就业相关法律、法规、规则和 + 标准。如果该司法管辖区没有此类法律、法规、规章和标准或其法律、法规、规章和标准不可 + 执行,则个人或法人实体必须遵守国际劳工标准的核心公约。 +3. 个人或法人不得以任何方式诱导或强迫其全职或兼职员工或其独立承包人以口头或书面形式同 + 意直接或间接限制、削弱或放弃其所拥有的,受相关与劳动和就业有关的法律、法规、规则和 + 标准保护的权利或补救措施,无论该等书面或口头协议是否被该司法管辖区的法律所承认,该 + 等个人或法人实体也不得以任何方法限制其雇员或独立承包人向版权持有人或监督许可证合规 + 情况的有关当局报告或投诉上述违反许可证的行为的权利。 + +该授权作品是"按原样"提供,不做任何明示或暗示的保证,包括但不限于对适销性、特定用途适用 +性和非侵权性的保证。在任何情况下,无论是在合同诉讼、侵权诉讼或其他诉讼中,版权持有人均 +不承担因本软件或本软件的使用或其他交易而产生、引起或与之相关的任何索赔、损害或其他责任。 + + +------------------------- ENGLISH ------------------------------ + + +Copyright (c) <2023> + +Anti 996 License Version 1.0 (Draft) + +Permission is hereby granted to any individual or legal entity obtaining a copy +of this licensed work (including the source code, documentation and/or related +items, hereinafter collectively referred to as the "licensed work"), free of +charge, to deal with the licensed work for any purpose, including without +limitation, the rights to use, reproduce, modify, prepare derivative works of, +publish, distribute and sublicense the licensed work, subject to the following +conditions: + +1. The individual or the legal entity must conspicuously display, without + modification, this License on each redistributed or derivative copy of the + Licensed Work. + +2. The individual or the legal entity must strictly comply with all applicable + laws, regulations, rules and standards of the jurisdiction relating to + labor and employment where the individual is physically located or where + the individual was born or naturalized; or where the legal entity is + registered or is operating (whichever is stricter). In case that the + jurisdiction has no such laws, regulations, rules and standards or its + laws, regulations, rules and standards are unenforceable, the individual + or the legal entity are required to comply with Core International Labor + Standards. + +3. The individual or the legal entity shall not induce or force its + employee(s), whether full-time or part-time, or its independent + contractor(s), in any methods, to agree in oral or written form, + to directly or indirectly restrict, weaken or relinquish his or + her rights or remedies under such laws, regulations, rules and + standards relating to labor and employment as mentioned above, + no matter whether such written or oral agreement are enforceable + under the laws of the said jurisdiction, nor shall such individual + or the legal entity limit, in any methods, the rights of its employee(s) + or independent contractor(s) from reporting or complaining to the copyright + holder or relevant authorities monitoring the compliance of the license + about its violation(s) of the said license. + +THE LICENSED WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT +HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ANY WAY CONNECTION +WITH THE LICENSED WORK OR THE USE OR OTHER DEALINGS IN THE LICENSED WORK. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 000000000..40f7fc748 --- /dev/null +++ b/README.md @@ -0,0 +1,204 @@ +
+预览 + +

ChatGPT Next Web

+ +一键免费部署你的私人 ChatGPT 网页应用。 + +One-Click to deploy your own ChatGPT web UI. + +[演示 Demo](https://chat-gpt-next-web.vercel.app/) / [反馈 Issues](https://github.com/Yidadaa/ChatGPT-Next-Web/issues) / [加入 Discord](https://discord.gg/zrhvHCr79N) / [QQ 群](https://user-images.githubusercontent.com/16968934/228190818-7dd00845-e9b9-4363-97e5-44c507ac76da.jpeg) / [打赏开发者](https://user-images.githubusercontent.com/16968934/227772541-5bcd52d8-61b7-488c-a203-0330d8006e2b.jpg) / [Donate](#捐赠-donate-usdt) + +[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYidadaa%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=chatgpt-next-web&repository-name=ChatGPT-Next-Web) + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web) + +![主界面](./static/cover.png) + +
+ +## 主要功能 + +- 在 1 分钟内使用 Vercel **免费一键部署** +- 精心设计的 UI,响应式设计,支持深色模式 +- 极快的首屏加载速度(~85kb) +- 海量的内置 prompt 列表,来自[中文](https://github.com/PlexPt/awesome-chatgpt-prompts-zh)和[英文](https://github.com/f/awesome-chatgpt-prompts) +- 自动压缩上下文聊天记录,在节省 Token 的同时支持超长对话 +- 一键导出聊天记录,完整的 Markdown 支持 +- 拥有自己的域名?好上加好,绑定后即可在任何地方**无障碍**快速访问 + +## Features + +- **Deploy for free with one-click** on Vercel in under 1 minute +- Responsive design, and dark mode +- Fast first screen loading speed (~85kb) +- Awesome prompts powered by [awesome-chatgpt-prompts-zh](https://github.com/PlexPt/awesome-chatgpt-prompts-zh) and [awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts) +- Automatically compresses chat history to support long conversations while also saving your tokens +- One-click export all chat history with full Markdown support + +## 开发计划 Roadmap +- System Prompt: pin a user defined prompt as system prompt 为每个对话设置系统 Prompt [#138](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/138) +- User Prompt: user can edit and save custom prompts to prompt list 允许用户自行编辑内置 Prompt 列表 +- Self-host Model: support llama, alpaca, ChatGLM, BELLE etc. 支持自部署的大语言模型 +- Plugins: support network search, caculator, any other apis etc. 插件机制,支持联网搜索、计算器、调用其他平台 api [#165](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/165) + +### 不会开发的功能 Not in Plan +- User login, accounts, cloud sync 用户登录、账号管理、消息云同步 +- UI text customize 界面文字自定义 + +## 开始使用 + +1. 准备好你的 [OpenAI API Key](https://platform.openai.com/account/api-keys); +2. 点击右侧按钮开始部署: + [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYidadaa%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=chatgpt-next-web&repository-name=ChatGPT-Next-Web),直接使用 Github 账号登录即可,记得在环境变量页填入 API Key; +3. 部署完毕后,即可开始使用; +4. (可选)[绑定自定义域名](https://vercel.com/docs/concepts/projects/domains/add-a-domain):Vercel 分配的域名 DNS 在某些区域被污染了,绑定自定义域名即可直连。 + +## Get Started + +1. Get [OpenAI API Key](https://platform.openai.com/account/api-keys); +2. Click + [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYidadaa%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=chatgpt-next-web&repository-name=ChatGPT-Next-Web); +3. Enjoy :) + +## 保持更新 Keep Updated + +如果你按照上述步骤一键部署了自己的项目,可能会发现总是提示“存在更新”的问题,这是由于 Vercel 会默认为你创建一个新项目而不是 fork 本项目,这会导致无法正确地检测更新。 +推荐你按照下列步骤重新部署: + +- 删除掉原先的 repo; +- fork 本项目; +- 前往 vercel 控制台,删除掉原先的 project,然后新建 project,选择你刚刚 fork 出来的项目重新进行部署即可; +- 在重新部署的过程中,请手动添加名为 `OPENAI_API_KEY` 的环境变量,并填入你的 api key 作为值。 + +本项目会持续更新,如果你想让代码库总是保持更新,可以查看 [Github 的文档](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork) 了解如何让 fork 的项目与上游代码同步,建议定期进行同步操作以获得新功能。 + +你可以 star/watch 本项目或者 follow 作者来及时获得新功能更新通知。 + +If you have deployed your own project with just one click following the steps above, you may encounter the issue of "Updates Available" constantly showing up. This is because Vercel will create a new project for you by default instead of forking this project, resulting in the inability to detect updates correctly. + +We recommend that you follow the steps below to re-deploy: + +- Delete the original repo; +- Fork this project; +- Go to the Vercel dashboard, delete the original project, then create a new project and select the project you just forked to redeploy; +- Please manually add an environment variable named `OPENAI_API_KEY` and enter your API key as the value during the redeploy process. + +This project will be continuously maintained. If you want to keep the code repository up to date, you can check out the [Github documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork) to learn how to synchronize a forked project with upstream code. It is recommended to perform synchronization operations regularly. + +You can star or watch this project or follow author to get release notifictions in time. + +## 配置密码 Password + +本项目提供有限的权限控制功能,请在 Vercel 项目控制面板的环境变量页增加名为 `CODE` 的环境变量,值为用英文逗号分隔的自定义密码: + +``` +code1,code2,code3 +``` + +增加或修改该环境变量后,请**重新部署**项目使改动生效。 + +This project provides limited access control. Please add an environment variable named `CODE` on the vercel environment variables page. The value should be passwords separated by comma like this: + +``` +code1,code2,code3 +``` + +After adding or modifying this environment variable, please redeploy the project for the changes to take effect. + +## 环境变量 Environment Variables + +### `OPENAI_API_KEY` (required) + +OpanAI 密钥。 + +Your openai api key. + +### `CODE` (optional) + +访问密码,可选,可以使用逗号隔开多个密码。 + +Access passsword, separated by comma. + +### `BASE_URL` (optional) + +> Default: `api.openai.com` + +OpenAI 接口代理 URL。 + +Override openai api request base url. + +### `PROTOCOL` (optional) + +> Default: `https` + +> Values: `http` | `https` + +OpenAI 接口协议。 + +Override openai api request protocol. + +## 开发 Development + +点击下方按钮,开始二次开发: + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web) + +在开始写代码之前,需要在项目根目录新建一个 `.env.local` 文件,里面填入环境变量: + +Before starting development, you must create a new `.env.local` file at project root, and place your api key into it: + +``` +OPENAI_API_KEY= +``` + +### 本地开发 Local Development + +> 如果你是中国大陆用户,不建议在本地进行开发,除非你能够独立解决 OpenAI API 本地代理问题。 + +1. 安装 nodejs 和 yarn,具体细节请询问 ChatGPT; +2. 执行 `yarn install && yarn dev` 即可。 + +### 本地部署 Local Deployment + +```shell +bash <(curl -s https://raw.githubusercontent.com/Yidadaa/ChatGPT-Next-Web/main/scripts/setup.sh) +``` + +### 容器部署 Docker Deployment + +```shell +docker pull yidadaa/chatgpt-next-web + +docker run -d -p 3000:3000 -e OPENAI_API_KEY="" -e CODE="" yidadaa/chatgpt-next-web +``` + +## 截图 Screenshots + +![设置 Settings](./static/settings.png) + +![更多展示 More](./static/more.png) + + +## 捐赠 Donate USDT +> BNB Smart Chain (BEP 20) +``` +0x67cD02c7EB62641De576a1fA3EdB32eA0c3ffD89 +``` + +## 鸣谢 Special Thanks + +### 捐赠者 Sponsor + +[@mushan0x0](https://github.com/mushan0x0) +[@ClarenceDan](https://github.com/ClarenceDan) +[@zhangjia](https://github.com/zhangjia) +[@hoochanlon](https://github.com/hoochanlon) + +### 贡献者 Contributor + +[Contributors](https://github.com/Yidadaa/ChatGPT-Next-Web/graphs/contributors) + +## LICENSE + +[Anti 996 License](https://github.com/kattgu7/Anti-996-License/blob/master/LICENSE_CN_EN) diff --git a/app/api/access.ts b/app/api/access.ts new file mode 100644 index 000000000..d3e4c9cf9 --- /dev/null +++ b/app/api/access.ts @@ -0,0 +1,17 @@ +import md5 from "spark-md5"; + +export function getAccessCodes(): Set { + const code = process.env.CODE; + + try { + const codes = (code?.split(",") ?? []) + .filter((v) => !!v) + .map((v) => md5.hash(v.trim())); + return new Set(codes); + } catch (e) { + return new Set(); + } +} + +export const ACCESS_CODES = getAccessCodes(); +export const IS_IN_DOCKER = process.env.DOCKER; diff --git a/app/api/chat-stream/route.ts b/app/api/chat-stream/route.ts new file mode 100644 index 000000000..e7bdfc5fb --- /dev/null +++ b/app/api/chat-stream/route.ts @@ -0,0 +1,52 @@ +import { createParser } from "eventsource-parser"; +import { NextRequest } from "next/server"; +import { requestOpenai } from "../common"; + +async function createStream(req: NextRequest) { + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + + const res = await requestOpenai(req); + + const stream = new ReadableStream({ + async start(controller) { + function onParse(event: any) { + if (event.type === "event") { + const data = event.data; + // https://beta.openai.com/docs/api-reference/completions/create#completions/create-stream + if (data === "[DONE]") { + controller.close(); + return; + } + try { + const json = JSON.parse(data); + const text = json.choices[0].delta.content; + const queue = encoder.encode(text); + controller.enqueue(queue); + } catch (e) { + controller.error(e); + } + } + } + + const parser = createParser(onParse); + for await (const chunk of res.body as any) { + parser.feed(decoder.decode(chunk)); + } + }, + }); + return stream; +} + +export async function POST(req: NextRequest) { + try { + const stream = await createStream(req); + return new Response(stream); + } catch (error) { + console.error("[Chat Stream]", error); + } +} + +export const config = { + runtime: "edge", +}; diff --git a/app/api/common.ts b/app/api/common.ts new file mode 100644 index 000000000..842eeacaf --- /dev/null +++ b/app/api/common.ts @@ -0,0 +1,22 @@ +import { NextRequest } from "next/server"; + +const OPENAI_URL = "api.openai.com"; +const DEFAULT_PROTOCOL = "https"; +const PROTOCOL = process.env.PROTOCOL ?? DEFAULT_PROTOCOL; +const BASE_URL = process.env.BASE_URL ?? OPENAI_URL; + +export async function requestOpenai(req: NextRequest) { + const apiKey = req.headers.get("token"); + const openaiPath = req.headers.get("path"); + + console.log("[Proxy] ", openaiPath); + + return fetch(`${PROTOCOL}://${BASE_URL}/${openaiPath}`, { + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${apiKey}`, + }, + method: req.method, + body: req.body, + }); +} diff --git a/app/api/openai/route.ts b/app/api/openai/route.ts new file mode 100644 index 000000000..cc51dbfc9 --- /dev/null +++ b/app/api/openai/route.ts @@ -0,0 +1,30 @@ +import { NextRequest, NextResponse } from "next/server"; +import { requestOpenai } from "../common"; + +async function makeRequest(req: NextRequest) { + try { + const api = await requestOpenai(req); + const res = new NextResponse(api.body); + res.headers.set("Content-Type", "application/json"); + return res; + } catch (e) { + console.error("[OpenAI] ", req.body, e); + return NextResponse.json( + { + error: true, + msg: JSON.stringify(e), + }, + { + status: 500, + }, + ); + } +} + +export async function POST(req: NextRequest) { + return makeRequest(req); +} + +export async function GET(req: NextRequest) { + return makeRequest(req); +} diff --git a/app/api/openai/typing.ts b/app/api/openai/typing.ts new file mode 100644 index 000000000..8c4218467 --- /dev/null +++ b/app/api/openai/typing.ts @@ -0,0 +1,7 @@ +import type { + CreateChatCompletionRequest, + CreateChatCompletionResponse, +} from "openai"; + +export type ChatRequest = CreateChatCompletionRequest; +export type ChatReponse = CreateChatCompletionResponse; diff --git a/app/components/button.module.scss b/app/components/button.module.scss new file mode 100644 index 000000000..b882a0c1f --- /dev/null +++ b/app/components/button.module.scss @@ -0,0 +1,60 @@ +.icon-button { + background-color: var(--white); + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + padding: 10px; + + box-shadow: var(--card-shadow); + cursor: pointer; + transition: all 0.3s ease; + overflow: hidden; + user-select: none; +} + +.border { + border: var(--border-in-light); +} + +.icon-button:hover { + filter: brightness(0.9); + border-color: var(--primary); +} + +.icon-button-icon { + width: 16px; + height: 16px; + display: flex; + justify-content: center; + align-items: center; +} + +@media only screen and (max-width: 600px) { + .icon-button { + padding: 16px; + } +} + +@mixin dark-button { + div:not(:global(.no-dark))>.icon-button-icon { + filter: invert(0.5); + } + + .icon-button:hover { + filter: brightness(1.2); + } +} + +:global(.dark) { + @include dark-button; +} + +@media (prefers-color-scheme: dark) { + @include dark-button; +} + +.icon-button-text { + margin-left: 5px; + font-size: 12px; +} \ No newline at end of file diff --git a/app/components/button.tsx b/app/components/button.tsx new file mode 100644 index 000000000..43b699b68 --- /dev/null +++ b/app/components/button.tsx @@ -0,0 +1,28 @@ +import * as React from "react"; + +import styles from "./button.module.scss"; + +export function IconButton(props: { + onClick?: () => void; + icon: JSX.Element; + text?: string; + bordered?: boolean; + className?: string; + title?: string; +}) { + return ( +
+
{props.icon}
+ {props.text && ( +
{props.text}
+ )} +
+ ); +} diff --git a/app/components/home.module.scss b/app/components/home.module.scss new file mode 100644 index 000000000..764805d80 --- /dev/null +++ b/app/components/home.module.scss @@ -0,0 +1,452 @@ +@import "./window.scss"; + +@mixin container { + background-color: var(--white); + border: var(--border-in-light); + border-radius: 20px; + box-shadow: var(--shadow); + color: var(--black); + background-color: var(--white); + min-width: 600px; + min-height: 480px; + max-width: 900px; + + display: flex; + overflow: hidden; + box-sizing: border-box; + + width: var(--window-width); + height: var(--window-height); +} + +.container { + @include container(); +} + +@media only screen and (min-width: 600px) { + .tight-container { + --window-width: 100vw; + --window-height: var(--full-height); + --window-content-width: calc(100% - var(--sidebar-width)); + + @include container(); + + max-width: 100vw; + max-height: var(--full-height); + + border-radius: 0; + } +} + +.sidebar { + top: 0; + width: var(--sidebar-width); + box-sizing: border-box; + padding: 20px; + background-color: var(--second); + display: flex; + flex-direction: column; + box-shadow: inset -2px 0px 2px 0px rgb(0, 0, 0, 0.05); +} + +.window-content { + width: var(--window-content-width); + height: 100%; + display: flex; + flex-direction: column; +} + +.mobile { + display: none; +} + +@media only screen and (max-width: 600px) { + .container { + min-height: unset; + min-width: unset; + max-height: unset; + min-width: unset; + border: 0; + border-radius: 0; + } + + .sidebar { + position: absolute; + left: -100%; + z-index: 999; + height: var(--full-height); + transition: all ease 0.3s; + box-shadow: none; + } + + .sidebar-show { + left: 0; + } + + .mobile { + display: block; + } +} + +.sidebar-header { + position: relative; + padding-top: 20px; + padding-bottom: 20px; +} + +.sidebar-logo { + position: absolute; + right: 0; + bottom: 18px; +} + +.sidebar-title { + font-size: 20px; + font-weight: bold; +} + +.sidebar-sub-title { + font-size: 12px; + font-weight: 400px; +} + +.sidebar-body { + flex: 1; + overflow: auto; +} + +.chat-list { +} + +.chat-item { + padding: 10px 14px; + background-color: var(--white); + border-radius: 10px; + margin-bottom: 10px; + box-shadow: var(--card-shadow); + transition: all 0.3s ease; + cursor: pointer; + user-select: none; + border: 2px solid transparent; + position: relative; + overflow: hidden; +} + +@keyframes slide-in { + from { + opacity: 0; + transform: translateY(20px); + } + + to { + opacity: 1; + transform: translateY(0px); + } +} + +.chat-item:hover { + background-color: var(--hover-color); +} + +.chat-item-selected { + border-color: var(--primary); +} + +.chat-item-title { + font-size: 14px; + font-weight: bolder; + display: block; + width: 200px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.chat-item-delete { + position: absolute; + top: 10px; + right: -20px; + transition: all ease 0.3s; + opacity: 0; +} + +.chat-item:hover > .chat-item-delete { + opacity: 0.5; + right: 10px; +} + +.chat-item:hover > .chat-item-delete:hover { + opacity: 1; +} + +.chat-item-info { + display: flex; + justify-content: space-between; + color: rgb(166, 166, 166); + font-size: 12px; + margin-top: 8px; +} + +.chat-item-count { +} + +.chat-item-date { +} + +.sidebar-tail { + display: flex; + justify-content: space-between; + padding-top: 20px; +} + +.sidebar-actions { + display: inline-flex; +} + +.sidebar-action:not(:last-child) { + margin-right: 15px; +} + +.chat { + display: flex; + flex-direction: column; + position: relative; + height: 100%; +} + +.chat-body { + flex: 1; + overflow: auto; + padding: 20px; +} + +.chat-body-title { + cursor: pointer; + + &:hover { + text-decoration: underline; + } +} + +.chat-message { + display: flex; + flex-direction: row; +} + +.chat-message-user { + display: flex; + flex-direction: row-reverse; +} + +.chat-message-container { + max-width: var(--message-max-width); + display: flex; + flex-direction: column; + align-items: flex-start; + animation: slide-in ease 0.3s; + + &:hover { + .chat-message-top-actions { + opacity: 1; + right: 10px; + pointer-events: all; + } + } +} + +.chat-message-user > .chat-message-container { + align-items: flex-end; +} + +.chat-message-avatar { + margin-top: 20px; +} + +.chat-message-status { + font-size: 12px; + color: #aaa; + line-height: 1.5; + margin-top: 5px; +} + +.user-avtar { + height: 30px; + width: 30px; + display: flex; + align-items: center; + justify-content: center; + border: var(--border-in-light); + box-shadow: var(--card-shadow); + border-radius: 10px; +} + +.chat-message-item { + box-sizing: border-box; + max-width: 100%; + margin-top: 10px; + border-radius: 10px; + background-color: rgba(0, 0, 0, 0.05); + padding: 10px; + font-size: 14px; + user-select: text; + word-break: break-word; + border: var(--border-in-light); + position: relative; +} + +.chat-message-top-actions { + font-size: 12px; + position: absolute; + right: 20px; + top: -26px; + left: 100px; + transition: all ease 0.3s; + opacity: 0; + pointer-events: none; + + display: flex; + flex-direction: row-reverse; + + .chat-message-top-action { + opacity: 0.5; + color: var(--black); + white-space: nowrap; + cursor: pointer; + + &:hover { + opacity: 1; + } + + &:not(:first-child) { + margin-right: 10px; + } + } +} + +.chat-message-user > .chat-message-container > .chat-message-item { + background-color: var(--second); +} + +.chat-message-actions { + display: flex; + flex-direction: row-reverse; + width: 100%; + padding-top: 5px; + box-sizing: border-box; + font-size: 12px; +} + +.chat-message-action-date { + color: #aaa; +} + +.chat-input-panel { + width: 100%; + padding: 20px; + box-sizing: border-box; + flex-direction: column; +} + +@mixin single-line { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.prompt-hints { + min-height: 20px; + width: 100%; + max-height: 50vh; + overflow: auto; + display: flex; + flex-direction: column-reverse; + + background-color: var(--white); + border: var(--border-in-light); + border-radius: 10px; + margin-bottom: 10px; + box-shadow: var(--shadow); + + .prompt-hint { + color: var(--black); + padding: 6px 10px; + animation: slide-in ease 0.3s; + cursor: pointer; + transition: all ease 0.3s; + border: transparent 1px solid; + margin: 4px; + border-radius: 8px; + + &:not(:last-child) { + margin-top: 0; + } + + .hint-title { + font-size: 12px; + font-weight: bolder; + + @include single-line(); + } + .hint-content { + font-size: 12px; + + @include single-line(); + } + + &-selected, + &:hover { + border-color: var(--primary); + } + } +} + +.chat-input-panel-inner { + display: flex; + flex: 1; +} + +.chat-input { + height: 100%; + width: 100%; + border-radius: 10px; + border: var(--border-in-light); + box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.03); + background-color: var(--white); + color: var(--black); + font-family: inherit; + padding: 10px 14px 50px; + resize: none; + outline: none; +} + +@media only screen and (max-width: 600px) { + .chat-input { + font-size: 16px; + } +} + +.chat-input:focus { + border: 1px solid var(--primary); +} + +.chat-input-send { + background-color: var(--primary); + color: white; + + position: absolute; + right: 30px; + bottom: 30px; +} + +.export-content { + white-space: break-spaces; +} + +.loading-content { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + height: 100%; + width: 100%; +} diff --git a/app/components/home.tsx b/app/components/home.tsx new file mode 100644 index 000000000..7ed35dfbe --- /dev/null +++ b/app/components/home.tsx @@ -0,0 +1,711 @@ +"use client"; + +import { useState, useRef, useEffect, useLayoutEffect } from "react"; +import { useDebouncedCallback } from "use-debounce"; + +import { IconButton } from "./button"; +import styles from "./home.module.scss"; + +import SettingsIcon from "../icons/settings.svg"; +import GithubIcon from "../icons/github.svg"; +import ChatGptIcon from "../icons/chatgpt.svg"; +import SendWhiteIcon from "../icons/send-white.svg"; +import BrainIcon from "../icons/brain.svg"; +import ExportIcon from "../icons/export.svg"; +import BotIcon from "../icons/bot.svg"; +import AddIcon from "../icons/add.svg"; +import DeleteIcon from "../icons/delete.svg"; +import LoadingIcon from "../icons/three-dots.svg"; +import MenuIcon from "../icons/menu.svg"; +import CloseIcon from "../icons/close.svg"; +import CopyIcon from "../icons/copy.svg"; +import DownloadIcon from "../icons/download.svg"; + +import { Message, SubmitKey, useChatStore, ChatSession } from "../store"; +import { showModal, showToast } from "./ui-lib"; +import { + copyToClipboard, + downloadAs, + isIOS, + isMobileScreen, + selectOrCopy, +} from "../utils"; +import Locale from "../locales"; + +import dynamic from "next/dynamic"; +import { REPO_URL } from "../constant"; +import { ControllerPool } from "../requests"; +import { Prompt, usePromptStore } from "../store/prompt"; + +export function Loading(props: { noLogo?: boolean }) { + return ( +
+ {!props.noLogo && } + +
+ ); +} + +const Markdown = dynamic(async () => (await import("./markdown")).Markdown, { + loading: () => , +}); + +const Settings = dynamic(async () => (await import("./settings")).Settings, { + loading: () => , +}); + +const Emoji = dynamic(async () => (await import("emoji-picker-react")).Emoji, { + loading: () => , +}); + +export function Avatar(props: { role: Message["role"] }) { + const config = useChatStore((state) => state.config); + + if (props.role === "assistant") { + return ; + } + + return ( +
+ +
+ ); +} + +export function ChatItem(props: { + onClick?: () => void; + onDelete?: () => void; + title: string; + count: number; + time: string; + selected: boolean; +}) { + return ( +
+
{props.title}
+
+
+ {Locale.ChatItem.ChatItemCount(props.count)} +
+
{props.time}
+
+
+ +
+
+ ); +} + +export function ChatList() { + const [sessions, selectedIndex, selectSession, removeSession] = useChatStore( + (state) => [ + state.sessions, + state.currentSessionIndex, + state.selectSession, + state.removeSession, + ], + ); + + return ( +
+ {sessions.map((item, i) => ( + selectSession(i)} + onDelete={() => confirm(Locale.Home.DeleteChat) && removeSession(i)} + /> + ))} +
+ ); +} + +function useSubmitHandler() { + const config = useChatStore((state) => state.config); + const submitKey = config.submitKey; + + const shouldSubmit = (e: React.KeyboardEvent) => { + if (e.key !== "Enter") return false; + if (e.key === "Enter" && e.nativeEvent.isComposing) return false; + return ( + (config.submitKey === SubmitKey.AltEnter && e.altKey) || + (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) || + (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) || + (config.submitKey === SubmitKey.MetaEnter && e.metaKey) || + (config.submitKey === SubmitKey.Enter && + !e.altKey && + !e.ctrlKey && + !e.shiftKey && + !e.metaKey) + ); + }; + + return { + submitKey, + shouldSubmit, + }; +} + +export function PromptHints(props: { + prompts: Prompt[]; + onPromptSelect: (prompt: Prompt) => void; +}) { + if (props.prompts.length === 0) return null; + + return ( +
+ {props.prompts.map((prompt, i) => ( +
props.onPromptSelect(prompt)} + > +
{prompt.title}
+
{prompt.content}
+
+ ))} +
+ ); +} + +export function Chat(props: { + showSideBar?: () => void; + sideBarShowing?: boolean; +}) { + type RenderMessage = Message & { preview?: boolean }; + + const chatStore = useChatStore(); + const [session, sessionIndex] = useChatStore((state) => [ + state.currentSession(), + state.currentSessionIndex, + ]); + const fontSize = useChatStore((state) => state.config.fontSize); + + const inputRef = useRef(null); + const [userInput, setUserInput] = useState(""); + const [isLoading, setIsLoading] = useState(false); + const { submitKey, shouldSubmit } = useSubmitHandler(); + + // prompt hints + const promptStore = usePromptStore(); + const [promptHints, setPromptHints] = useState([]); + const onSearch = useDebouncedCallback( + (text: string) => { + setPromptHints(promptStore.search(text)); + }, + 100, + { leading: true, trailing: true }, + ); + + const onPromptSelect = (prompt: Prompt) => { + setUserInput(prompt.content); + setPromptHints([]); + inputRef.current?.focus(); + }; + + const scrollInput = () => { + const dom = inputRef.current; + if (!dom) return; + const paddingBottomNum: number = parseInt( + window.getComputedStyle(dom).paddingBottom, + 10, + ); + dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum; + }; + + // only search prompts when user input is short + const SEARCH_TEXT_LIMIT = 30; + const onInput = (text: string) => { + scrollInput(); + setUserInput(text); + const n = text.trim().length; + + // clear search results + if (n === 0) { + setPromptHints([]); + } else if (!chatStore.config.disablePromptHint && n < SEARCH_TEXT_LIMIT) { + // check if need to trigger auto completion + if (text.startsWith("/") && text.length > 1) { + onSearch(text.slice(1)); + } + } + }; + + // submit user input + const onUserSubmit = () => { + if (userInput.length <= 0) return; + setIsLoading(true); + chatStore.onUserInput(userInput).then(() => setIsLoading(false)); + setUserInput(""); + setPromptHints([]); + inputRef.current?.focus(); + }; + + // stop response + const onUserStop = (messageIndex: number) => { + console.log(ControllerPool, sessionIndex, messageIndex); + ControllerPool.stop(sessionIndex, messageIndex); + }; + + // check if should send message + const onInputKeyDown = (e: React.KeyboardEvent) => { + if (shouldSubmit(e)) { + onUserSubmit(); + e.preventDefault(); + } + }; + const onRightClick = (e: any, message: Message) => { + // auto fill user input + if (message.role === "user") { + setUserInput(message.content); + } + + // copy to clipboard + if (selectOrCopy(e.currentTarget, message.content)) { + e.preventDefault(); + } + }; + + const onResend = (botIndex: number) => { + // find last user input message and resend + for (let i = botIndex; i >= 0; i -= 1) { + if (messages[i].role === "user") { + setIsLoading(true); + chatStore + .onUserInput(messages[i].content) + .then(() => setIsLoading(false)); + inputRef.current?.focus(); + return; + } + } + }; + + // for auto-scroll + const latestMessageRef = useRef(null); + const [autoScroll, setAutoScroll] = useState(true); + + const config = useChatStore((state) => state.config); + + // preview messages + const messages = (session.messages as RenderMessage[]) + .concat( + isLoading + ? [ + { + role: "assistant", + content: "……", + date: new Date().toLocaleString(), + preview: true, + }, + ] + : [], + ).concat( + userInput.length > 0 && config.sendPreviewBubble + ? [ + { + role: "user", + content: userInput, + date: new Date().toLocaleString(), + preview: false, + }, + ] + : [], + ); + + // auto scroll + useLayoutEffect(() => { + setTimeout(() => { + const dom = latestMessageRef.current; + const inputDom = inputRef.current; + + // only scroll when input overlaped message body + let shouldScroll = true; + if (dom && inputDom) { + const domRect = dom.getBoundingClientRect(); + const inputRect = inputDom.getBoundingClientRect(); + shouldScroll = domRect.top > inputRect.top; + } + + if (dom && autoScroll && shouldScroll) { + dom.scrollIntoView({ + block: "end", + }); + } + }, 500); + }); + + return ( +
+
+
+
{ + const newTopic = prompt(Locale.Chat.Rename, session.topic); + if (newTopic && newTopic !== session.topic) { + chatStore.updateCurrentSession( + (session) => (session.topic = newTopic!), + ); + } + }} + > + {session.topic} +
+
+ {Locale.Chat.SubTitle(session.messages.length)} +
+
+
+
+ } + bordered + title={Locale.Chat.Actions.ChatList} + onClick={props?.showSideBar} + /> +
+
+ } + bordered + title={Locale.Chat.Actions.CompressedHistory} + onClick={() => { + showMemoryPrompt(session); + }} + /> +
+
+ } + bordered + title={Locale.Chat.Actions.Export} + onClick={() => { + exportMessages(session.messages, session.topic); + }} + /> +
+
+
+ +
+ {messages.map((message, i) => { + const isUser = message.role === "user"; + + return ( +
+
+
+ +
+ {(message.preview || message.streaming) && ( +
+ {Locale.Chat.Typing} +
+ )} +
+ {!isUser && + !(message.preview || message.content.length === 0) && ( +
+ {message.streaming ? ( +
onUserStop(i)} + > + {Locale.Chat.Actions.Stop} +
+ ) : ( +
onResend(i)} + > + {Locale.Chat.Actions.Retry} +
+ )} + +
copyToClipboard(message.content)} + > + {Locale.Chat.Actions.Copy} +
+
+ )} + {(message.preview || message.content.length === 0) && + !isUser ? ( + + ) : ( +
onRightClick(e, message)} + onDoubleClickCapture={() => { + if (!isMobileScreen()) return; + setUserInput(message.content); + }} + > + +
+ )} +
+ {!isUser && !message.preview && ( +
+
+ {message.date.toLocaleString()} +
+
+ )} +
+
+ ); + })} +
+ - +
+
+ +
+ +
+