diff --git a/.env.local.config b/.env.local.config deleted file mode 100644 index 25b8d6c908e67c222ce330c21d4b4714790be9fd..0000000000000000000000000000000000000000 --- a/.env.local.config +++ /dev/null @@ -1,3 +0,0 @@ -OPENAI_API_KEY="" -WANJUAN_TOKEN="" -COOKIES="" diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 08975255475d03bc508c93cb1317ae3827d683d1..0000000000000000000000000000000000000000 --- a/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -public/serviceWorker.js \ No newline at end of file diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index d229e86f2507ceae85d87a78487cb491eceeb5dd..0000000000000000000000000000000000000000 --- a/.eslintrc.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "next/core-web-vitals", - "plugins": ["prettier"] -} diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index c7d9f3332a950355d5a77d85000f05e6f45435ea..0000000000000000000000000000000000000000 --- a/.gitattributes +++ /dev/null @@ -1,34 +0,0 @@ -*.7z filter=lfs diff=lfs merge=lfs -text -*.arrow filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.bz2 filter=lfs diff=lfs merge=lfs -text -*.ckpt filter=lfs diff=lfs merge=lfs -text -*.ftz filter=lfs diff=lfs merge=lfs -text -*.gz filter=lfs diff=lfs merge=lfs -text -*.h5 filter=lfs diff=lfs merge=lfs -text -*.joblib filter=lfs diff=lfs merge=lfs -text -*.lfs.* filter=lfs diff=lfs merge=lfs -text -*.mlmodel filter=lfs diff=lfs merge=lfs -text -*.model filter=lfs diff=lfs merge=lfs -text -*.msgpack filter=lfs diff=lfs merge=lfs -text -*.npy filter=lfs diff=lfs merge=lfs -text -*.npz filter=lfs diff=lfs merge=lfs -text -*.onnx filter=lfs diff=lfs merge=lfs -text -*.ot filter=lfs diff=lfs merge=lfs -text -*.parquet filter=lfs diff=lfs merge=lfs -text -*.pb filter=lfs diff=lfs merge=lfs -text -*.pickle filter=lfs diff=lfs merge=lfs -text -*.pkl filter=lfs diff=lfs merge=lfs -text -*.pt filter=lfs diff=lfs merge=lfs -text -*.pth filter=lfs diff=lfs merge=lfs -text -*.rar filter=lfs diff=lfs merge=lfs -text -*.safetensors filter=lfs diff=lfs merge=lfs -text -saved_model/**/* filter=lfs diff=lfs merge=lfs -text -*.tar.* filter=lfs diff=lfs merge=lfs -text -*.tflite filter=lfs diff=lfs merge=lfs -text -*.tgz filter=lfs diff=lfs merge=lfs -text -*.wasm filter=lfs diff=lfs merge=lfs -text -*.xz filter=lfs diff=lfs merge=lfs -text -*.zip filter=lfs diff=lfs merge=lfs -text -*.zst filter=lfs diff=lfs merge=lfs -text -*tfevents* filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 0a3e52afa9f31d4bf5a419088423f38e60b5bc21..0000000000000000000000000000000000000000 --- a/.gitignore +++ /dev/null @@ -1,39 +0,0 @@ -# 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 deleted file mode 100644 index d81f2dab15cccb7467e68b7227570e32eb25ad61..0000000000000000000000000000000000000000 --- a/.gitpod.yml +++ /dev/null @@ -1,11 +0,0 @@ -# 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 deleted file mode 100644 index 0312b76025e218e6f4ff481e134b3766a60b0c6e..0000000000000000000000000000000000000000 --- a/.husky/pre-commit +++ /dev/null @@ -1,4 +0,0 @@ -#!/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 deleted file mode 100644 index 023bf16ab0dfb2280be09be7e714bddc575eda17..0000000000000000000000000000000000000000 --- a/.lintstagedrc.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "./app/**/*.{js,ts,jsx,tsx,json,html,css,scss,md}": [ - "eslint --fix", - "prettier --write" - ] -} \ No newline at end of file diff --git a/.prettierrc.js b/.prettierrc.js deleted file mode 100644 index 95cc75ffaecbf894ac8bcffafba9805ad7d6d55f..0000000000000000000000000000000000000000 --- a/.prettierrc.js +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index bd3337f97172bb8064210f095bcd7d7a0ae4a29d..0000000000000000000000000000000000000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "typescript.tsdk": "node_modules\\typescript\\lib", - "typescript.enablePromptUseWorkspaceTsdk": true -} \ No newline at end of file diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 002bd346a570af1a7d0b0def4ef182743babbea2..0000000000000000000000000000000000000000 --- a/Dockerfile +++ /dev/null @@ -1,46 +0,0 @@ -FROM node:18-alpine AS base - -FROM base AS deps - -RUN apk add --no-cache libc6-compat - -WORKDIR /app - -COPY package.json yarn.lock* package-lock.json* ./ - -RUN \ - if [ -f yarn.lock ]; then yarn --frozen-lockfile; \ - elif [ -f package-lock.json ]; then npm ci; \ - else echo "Lockfile not found." && exit 1; \ - fi - -FROM base AS builder - -RUN apk update && apk add --no-cache git - -ENV OPENAI_API_KEY="" -ENV COOKIES="" -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 COOKIES="" -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 deleted file mode 100644 index 4f00efc87911909c70fda5b1af003f9dd16b8909..0000000000000000000000000000000000000000 --- a/LICENSE +++ /dev/null @@ -1,75 +0,0 @@ -版权所有(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 deleted file mode 100644 index ca99eecad56c16c2e937efefe3d2b45ee4979358..0000000000000000000000000000000000000000 --- a/README.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -title: ChatGpt Web -emoji: 📊 -colorFrom: green -colorTo: blue -sdk: docker -pinned: false -license: openrail -app_port: 3000 ---- - -Check out the configuration reference at https://huggingface.co./docs/hub/spaces-config-reference - -
-预览 - -

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) - -[![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&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) - -![主界面](../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 - -## 使用 - -1. 准备好你的 [OpenAI API Key](https://platform.openai.com/account/api-keys)、NewBingCookie、WanJuanToken; -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&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&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. - -## 访问控制 Access Control - -本项目提供有限的权限控制功能,请在环境变量页增加名为 `CODE` 的环境变量,值为用英文逗号分隔的自定义控制码: - -``` -code1,code2,code3 -``` - -增加或修改该环境变量后,请**重新部署**项目使改动生效。 - -This project provides limited access control. Please add an environment variable named `CODE` on the environment variables page. The value should be a custom control code 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. - -## 开发 Development - -点击下方按钮,开始二次开发: - -[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web) - -在开始写代码之前,需要在项目根目录新建一个 `.env.local` 文件,里面填入环境变量: - -新必应只需要名为_u的cookie的值 - -Before starting development, you must create a new `.env.local` file at project root, and place your api key into it: - -``` -OPENAI_API_KEY= -CODE= -COOKIES= -WANJUAN_TOKEN= -``` - -### 本地开发 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](../ChatGPT-Next-Web/static/settings.png) - -![更多展示 More](../ChatGPT-Next-Web/static/more.png) - -## 说明 Attention - -本项目的演示地址所用的 OpenAI 账户的免费额度将于 2023-04-01 过期,届时将无法通过演示地址在线体验。 - -如果你想贡献出自己的 API Key,可以通过作者主页的邮箱发送给作者,并标注过期时间。 - -The free trial of the OpenAI account used by the demo will expire on April 1, 2023, and the demo will not be available at that time. - -If you would like to contribute your API key, you can email it to the author and indicate the expiration date of the API key. - -## 鸣谢 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) \ No newline at end of file diff --git a/app/api/access.ts b/app/api/access.ts deleted file mode 100644 index d3e4c9cf99b6cb94cc0ae3c84fa30ffadd1eef07..0000000000000000000000000000000000000000 --- a/app/api/access.ts +++ /dev/null @@ -1,17 +0,0 @@ -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-image/route.ts b/app/api/chat-image/route.ts deleted file mode 100644 index 8e5f5c48c5f75935044506eb6f5bbe03b60894d1..0000000000000000000000000000000000000000 --- a/app/api/chat-image/route.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { OpenAIApi, Configuration } from "openai"; -import { ChatImageRequest } from "../chat/typing"; - -export async function POST(req: Request) { - try { - let apiKey = process.env.OPENAI_API_KEY; - - const userApiKey = req.headers.get("token"); - if (userApiKey) { - apiKey = userApiKey; - console.log("user api key:" + apiKey); - } - - const openai = new OpenAIApi( - new Configuration({ - apiKey, - }), - ); - - const requestBody = (await req.json()) as ChatImageRequest; - const response = await openai.createImage({ - ...requestBody, - }); - console.log(response.data.data[0].url); - return new Response(JSON.stringify(response.data)); - } catch (e) { - console.error("[Chat] ", e); - return new Response(JSON.stringify(e)); - } -} diff --git a/app/api/chat-stream/route.ts b/app/api/chat-stream/route.ts deleted file mode 100644 index e7fe97fea79aae5258df2b6e9fae54f21a5ae2c0..0000000000000000000000000000000000000000 --- a/app/api/chat-stream/route.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { createParser } from "eventsource-parser"; -import { NextRequest } from "next/server"; - -async function createStream(req: NextRequest) { - const encoder = new TextEncoder(); - const decoder = new TextDecoder(); - - let apiKey = process.env.OPENAI_API_KEY; - - const userApiKey = req.headers.get("token"); - if (userApiKey) { - apiKey = userApiKey; - console.log("[Stream] using user api key:" + apiKey); - } - - const res = await fetch("https://api.openai.com/v1/chat/completions", { - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${apiKey}`, - }, - method: "POST", - body: req.body, - }); - - 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/chat/.gitignore b/app/api/chat/.gitignore deleted file mode 100644 index 1b8afd087bc223602956668a12c9b9b9249fd507..0000000000000000000000000000000000000000 --- a/app/api/chat/.gitignore +++ /dev/null @@ -1 +0,0 @@ -config.ts \ No newline at end of file diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts deleted file mode 100644 index 18c7db148fc0bd3de35f5f97aa2f8fbbe9439d07..0000000000000000000000000000000000000000 --- a/app/api/chat/route.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { OpenAIApi, Configuration } from "openai"; -import { ChatRequest } from "./typing"; - -export async function POST(req: Request) { - try { - let apiKey = process.env.OPENAI_API_KEY; - - const userApiKey = req.headers.get("token"); - if (userApiKey) { - apiKey = userApiKey; - } - - const openai = new OpenAIApi( - new Configuration({ - apiKey, - }) - ); - - const requestBody = (await req.json()) as ChatRequest; - const completion = await openai!.createChatCompletion({ - ...requestBody, - }); - - return new Response(JSON.stringify(completion.data)); - } catch (e) { - console.error("[Chat] ", e); - return new Response(JSON.stringify(e)); - } -} diff --git a/app/api/chat/typing.ts b/app/api/chat/typing.ts deleted file mode 100644 index 7ec057ce01fe055e10a5793316f6644fc567f54f..0000000000000000000000000000000000000000 --- a/app/api/chat/typing.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { - CreateChatCompletionRequest, - CreateChatCompletionResponse, - CreateImageRequest, - ImagesResponse, -} from "openai"; - -export type ChatRequest = CreateChatCompletionRequest; -export type ChatReponse = CreateChatCompletionResponse; -export type ChatImageRequest = CreateImageRequest; -export type ChatImagesResponse = ImagesResponse; diff --git a/app/api/newbing-image/route.ts b/app/api/newbing-image/route.ts deleted file mode 100644 index 599c6e6a1a6e52bfa2799279906c12a07b54d53f..0000000000000000000000000000000000000000 --- a/app/api/newbing-image/route.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { BingChat} from "../../bing-chat/build/index"; - -export async function POST(req: Request) { - try { - let cookies = process.env.COOKIES; - const api = new BingChat({ - cookie: cookies, - }); - const res = await api.createImage(await req.json()); - console.log(res) - return new Response(); - } catch (e) { - console.error("[NewBing] ", e); - return new Response(JSON.stringify(e)); - } -} diff --git a/app/api/newbing/route.ts b/app/api/newbing/route.ts deleted file mode 100644 index 7decbcd01e421daaeb45dec8b4acbcbfd4c60704..0000000000000000000000000000000000000000 --- a/app/api/newbing/route.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { BingChat, ChatMessage } from "../../bing-chat/build/index"; - -export async function POST(req: Request) { - try { - let cookies = process.env.COOKIES; - const api = new BingChat({ - cookie: cookies, - }); - let chat: ChatMessage = { - id: "", - text: "", - author: "bot", - conversationId: "", - clientId: "", - conversationSignature: "", - }; - const res: any = await bingAiMessageSendWrapper( - api, - await req.json(), - chat, - ); - // const res = await api.sendMessage(await req.json(), { - // // print the partial response as the AI is "typing" - // onProgress: (partialResponse) => { - // console.log(partialResponse.text); - // }, - // variant: "Precise", - // }); - // console.log(res['text']) - return new Response(res["text"]); - } catch (e) { - console.error("[NewBing] ", e); - return new Response(JSON.stringify(e)); - } -} - -/** - * @param { import("bing-chat").BingChat } client - * @param { string } message - * @param { import("bing-chat").ChatMessage } [session] - * @returns { Promise } - */ -function bingAiMessageSendWrapper( - client: BingChat, - message: string, - session: ChatMessage, -) { - const TIMEOUT_THRESHOLD = 120 * 1000; - return new Promise((resolve, reject) => { - let response = { - text: "", - }; - let responseText = ""; - let temp = { - time: new Date().valueOf(), - response: response, - }; - const verifyIfResponseChangedInterval = setInterval(() => { - if (new Date().valueOf() - temp.time > TIMEOUT_THRESHOLD) { - clearInterval(verifyIfResponseChangedInterval); - temp.response.text = responseText; - resolve(temp.response); - } - }, 500); - client - .sendMessage(message, { - ...session, - onProgress: (partialResponse) => { - temp.response = partialResponse; - responseText += partialResponse.text; - temp.time = new Date().valueOf(); - }, - }) - .then((response) => { - resolve(response); - }) - .catch((error) => { - reject(error); - }); - }); -} diff --git a/app/api/revchat/route.ts b/app/api/revchat/route.ts deleted file mode 100644 index 50290a270bd1d6be27ba737bb91ddaae30fee154..0000000000000000000000000000000000000000 --- a/app/api/revchat/route.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { createParser } from "eventsource-parser"; -import { NextRequest } from "next/server"; - -async function createStream(req: NextRequest) { - const encoder = new TextEncoder(); - const decoder = new TextDecoder(); - - const res = await fetch("http://lemurchat.anfans.cn/api/chat/conversation-trial", { - headers: { - "Content-Type": "application/json" - }, - method: "POST", - body: req.body, - }); - - const stream = new ReadableStream({ - async start(controller) { - function onParse(event: any) { - if (event.type === "event") { - const data = event.data; - if(event.id=="1"){ - let text1=data.slice(data.indexOf("content")) - const text = text1.slice(12,text1.indexOf("index")-6) - const queue = encoder.encode(text); - controller.enqueue(queue); - return; - } - // https://beta.openai.com/docs/api-reference/completions/create#completions/create-stream - try { - const json = JSON.parse(data); - // console.log(data.indexOf("content")) - if (data.indexOf("content")==-1) { - controller.close(); - return; - } - // console.log(event.data) - const text = JSON.parse(json.data.slice(5)).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/wanjuan/route.ts b/app/api/wanjuan/route.ts deleted file mode 100644 index bc697bf9f7f26b72b49421112c560cb5e0f9a854..0000000000000000000000000000000000000000 --- a/app/api/wanjuan/route.ts +++ /dev/null @@ -1,35 +0,0 @@ -export async function POST(req: Request) { - try { - let token = process.env.WANJUAN_TOKEN; - let body = { message: await req.json() }; - - console.log(JSON.stringify(body)); - let res = ""; - await fetch("http://47.94.237.159:8080/v1/wanjuan", { - method: "POST", - headers:{ - "Authorization":"Bearer "+token - }, - body: JSON.stringify(body), - }) - .then((response) => response.json()) - .then((data) => { - // console.log(data) - if (data["statusInfo"]["code"] == 0) { - // console.log("123123") - res = data["data"]["msgContent"]; - } else { - res = data["statusInfo"]["message"]; - } - }) - .catch((err) => { - console.error("[WanJuan] ", err); - res = "出错了请重试!"; - }); - // console.log("12312"+res); - return new Response(res); - } catch (e) { - console.error("[WanJuan] ", e); - return new Response(JSON.stringify(e)); - } -} diff --git a/app/bing-chat/build/index.d.ts b/app/bing-chat/build/index.d.ts deleted file mode 100644 index dcaac95700b380f17c6a7126d7476344376d292f..0000000000000000000000000000000000000000 --- a/app/bing-chat/build/index.d.ts +++ /dev/null @@ -1,275 +0,0 @@ -type Author = "user" | "bot"; -type SendMessageOptions = { - conversationId?: string; - clientId?: string; - conversationSignature?: string; - invocationId?: string; - messageType?: string; - variant?: string; - locale?: string; - market?: string; - region?: string; - location?: { - lat: number | string; - lng: number | string; - re?: string; - }; - onProgress?: (partialResponse: ChatMessage) => void; -}; -interface ChatMessage { - id: string; - text: string; - author: Author; - conversationId: string; - clientId: string; - conversationSignature: string; - conversationExpiryTime?: string; - invocationId?: string; - messageType?: string; - variant?: string; - detail?: ChatMessageFull | ChatMessagePartial; -} -interface ConversationResult { - conversationId: string; - clientId: string; - conversationSignature: string; - result: APIResult; -} -interface APIResult { - value: string; - message: null; -} -interface ChatUpdate { - type: 1; - target: string; - arguments: ChatUpdateArgument[]; -} -interface ChatUpdateArgument { - messages: ChatMessagePartial[]; - requestId: string; - result: null; -} -interface ChatMessagePartial { - text: string; - author: Author; - createdAt: string; - timestamp: string; - messageId: string; - offense: string; - adaptiveCards: AdaptiveCard[]; - sourceAttributions: any[]; - feedback: ChatMessageFeedback; - contentOrigin: string; - privacy?: null; - messageType?: string; -} -interface AdaptiveCard { - type: string; - version: string; - body: AdaptiveCardBody[]; -} -interface AdaptiveCardBody { - type: string; - text: string; - wrap: boolean; -} -interface ChatMessageFeedback { - tag: null; - updatedOn: null; - type: string; -} -interface ChatUpdateCompleteResponse { - type: 2; - invocationId: string; - item: ChatResponseItem; -} -interface ChatResponseItem { - messages: ChatMessageFull[]; - firstNewMessageIndex: number; - suggestedResponses: null; - conversationId: string; - requestId: string; - conversationExpiryTime: string; - telemetry: Telemetry; - result: ChatRequestResult; -} -interface ChatMessageFull { - text: string; - author: Author; - from?: ChatMessageFrom; - createdAt: string; - timestamp: string; - locale?: string; - market?: string; - region?: string; - location?: string; - locationHints?: LocationHint[]; - messageId: string; - requestId: string; - offense: string; - feedback: ChatMessageFeedback; - contentOrigin: string; - privacy?: null; - inputMethod?: string; - adaptiveCards?: AdaptiveCard[]; - sourceAttributions?: any[]; - suggestedResponses?: SuggestedResponse[]; - messageType?: string; -} -interface ChatMessageFrom { - id: string; - name: null; -} -interface LocationHint { - country: string; - countryConfidence: number; - state: string; - city: string; - cityConfidence: number; - zipCode: string; - timeZoneOffset: number; - dma: number; - sourceType: number; - center: Coords; - regionType: number; -} -interface Coords { - latitude: number; - longitude: number; - height: null; -} -interface SuggestedResponse { - text: string; - messageId: string; - messageType: string; - contentOrigin: string; - author?: Author; - createdAt?: string; - timestamp?: string; - offense?: string; - feedback?: ChatMessageFeedback; - privacy?: null; -} -interface ChatRequestResult { - value: string; - serviceVersion: string; -} -interface Telemetry { - metrics?: null; - startTime: string; -} -interface ChatRequest { - arguments: ChatRequestArgument[]; - invocationId: string; - target: string; - type: number; -} -interface ChatRequestArgument { - source: string; - optionsSets: string[]; - allowedMessageTypes: string[]; - sliceIds: any[]; - traceId: string; - isStartOfSession: boolean; - message: ChatRequestMessage; - conversationSignature: string; - participant: Participant; - conversationId: string; - previousMessages: PreviousMessage[]; -} -interface ChatRequestMessage { - locale: string; - market: string; - region?: string; - location?: string; - locationHints?: LocationHintChatRequestMessage[]; - timestamp: string; - author: Author; - inputMethod: string; - text: string; - messageType: string; -} -interface LocationHintChatRequestMessage { - country: string; - state: string; - city: string; - zipcode: string; - timezoneoffset: number; - dma: number; - countryConfidence: number; - cityConfidence: number; - Center: Center; - RegionType: number; - SourceType: number; -} -interface Center { - Latitude: number; - Longitude: number; -} -interface Participant { - id: string; -} -interface PreviousMessage { - text: string; - author: Author; - adaptiveCards: any[]; - suggestedResponses: SuggestedResponse[]; - messageId: string; - messageType: string; -} - -declare class BingChat { - protected _cookie: string; - protected _debug: boolean; - constructor(opts: { - cookie: string | undefined; - /** @defaultValue `false` **/ - debug?: boolean; - }); - /** - * Sends a message to Bing Chat, waits for the response to resolve, and returns - * the response. - * - * If you want to receive a stream of partial responses, use `opts.onProgress`. - * - * @param message - The prompt message to send - * @param opts.conversationId - Optional ID of a conversation to continue (defaults to a random UUID) - * @param opts.onProgress - Optional callback which will be invoked every time the partial response is updated - * - * @returns The response from Bing Chat - */ - sendMessage(text: string, opts?: SendMessageOptions): Promise; - createConversation(): Promise; - createImage(message: string): Array; -} - -export { - APIResult, - AdaptiveCard, - AdaptiveCardBody, - Author, - BingChat, - Center, - ChatMessage, - ChatMessageFeedback, - ChatMessageFrom, - ChatMessageFull, - ChatMessagePartial, - ChatRequest, - ChatRequestArgument, - ChatRequestMessage, - ChatRequestResult, - ChatResponseItem, - ChatUpdate, - ChatUpdateArgument, - ChatUpdateCompleteResponse, - ConversationResult, - Coords, - LocationHint, - LocationHintChatRequestMessage, - Participant, - PreviousMessage, - SendMessageOptions, - SuggestedResponse, - Telemetry, -}; diff --git a/app/bing-chat/build/index.js b/app/bing-chat/build/index.js deleted file mode 100644 index 9a08f287605143750d91e14bf4f18444b019efa0..0000000000000000000000000000000000000000 --- a/app/bing-chat/build/index.js +++ /dev/null @@ -1,307 +0,0 @@ -// src/bing-chat.ts -import { time } from "node:console"; -import crypto from "node:crypto"; -import WebSocket from "ws"; - -// src/fetch.ts -var fetch = globalThis.fetch; -if (typeof fetch !== "function") { - throw new Error("Invalid environment: global fetch not defined"); -} - -// src/bing-chat.ts -var terminalChar = ""; -var BingChat = class { - constructor(opts) { - const { cookie, debug = false } = opts; - this._cookie = cookie; - this._debug = !!debug; - if (!this._cookie) { - throw new Error("Bing cookie is required"); - } - } - /** - * Sends a message to Bing Chat, waits for the response to resolve, and returns - * the response. - * - * If you want to receive a stream of partial responses, use `opts.onProgress`. - * - * @param message - The prompt message to send - * @param opts.conversationId - Optional ID of a conversation to continue (defaults to a random UUID) - * @param opts.onProgress - Optional callback which will be invoked every time the partial response is updated - * - * @returns The response from Bing Chat - */ - async sendMessage(text, opts = {}) { - const { - invocationId = "1", - onProgress, - locale = "en-US", - market = "en-US", - region = "US", - location, - messageType = "Chat", - variant = "Balanced" - } = opts; - let { conversationId, clientId, conversationSignature } = opts; - const isStartOfSession = !(conversationId && clientId && conversationSignature); - if (isStartOfSession) { - const conversation = await this.createConversation(); - conversationId = conversation.conversationId; - clientId = conversation.clientId; - conversationSignature = conversation.conversationSignature; - } - const result = { - author: "bot", - id: crypto.randomUUID(), - conversationId, - clientId, - conversationSignature, - invocationId: `${parseInt(invocationId, 10) + 1}`, - text: "" - }; - const responseP = new Promise( - async (resolve, reject) => { - const chatWebsocketUrl = "wss://sydney.bing.com/sydney/ChatHub"; - const ws = new WebSocket(chatWebsocketUrl, { - perMessageDeflate: false, - headers: { - "accept-language": "en-US,en;q=0.9", - "cache-control": "no-cache", - pragma: "no-cache" - } - }); - let isFulfilled = false; - function cleanup() { - ws.close(); - ws.removeAllListeners(); - } - ws.on("error", (error) => { - console.warn("WebSocket error:", error); - cleanup(); - if (!isFulfilled) { - isFulfilled = true; - reject(new Error(`WebSocket error: ${error.toString()}`)); - } - }); - ws.on("close", () => { - }); - ws.on("open", () => { - ws.send(`{"protocol":"json","version":1}${terminalChar}`); - }); - let stage = 0; - ws.on("message", (data) => { - var _a, _b; - const objects = data.toString().split(terminalChar); - const messages = objects.map((object) => { - try { - return JSON.parse(object); - } catch (error) { - return object; - } - }).filter(Boolean); - if (!messages.length) { - return; - } - if (stage === 0) { - ws.send(`{"type":6}${terminalChar}`); - const traceId = crypto.randomBytes(16).toString("hex"); - const locationStr = location ? `lat:${location.lat};long:${location.lng};re=${location.re || "1000m"};` : void 0; - const optionsSets = [ - "nlu_direct_response_filter", - "deepleo", - "enable_debug_commands", - "disable_emoji_spoken_text", - "responsible_ai_policy_235", - 'enablemm', - 'trffovrd', - 'h3toppfp3', - 'forcerep', - 'cpcttl1d', - 'dv3sugg' - ]; - if (variant == "Balanced") { - optionsSets.push("galileo"); - optionsSets.push('glprompt') - } else if (variant == "Creative") { - optionsSets.push("h3imaginative"); - optionsSets.push('gencontentv3') - } else if (variant == "Precise") { - optionsSets.push("h3precise"); - } - const params = { - arguments: [ - { - source: "cib", - optionsSets, - allowedMessageTypes: [ - "Chat", - "InternalSearchQuery", - "InternalSearchResult", - "InternalLoaderMessage", - "RenderCardRequest", - "AdsQuery", - "SemanticSerp" - ], - sliceIds: [], - traceId, - isStartOfSession, - message: { - locale, - market, - region, - location: locationStr, - author: "user", - inputMethod: "Keyboard", - messageType, - text - }, - conversationSignature, - participant: { id: clientId }, - conversationId - } - ], - invocationId, - target: "chat", - type: 4 - }; - if (this._debug) { - console.log(chatWebsocketUrl, JSON.stringify(params, null, 2)); - } - ws.send(`${JSON.stringify(params)}${terminalChar}`); - ++stage; - return; - } - for (const message of messages) { - if (message.type === 1) { - const update = message; - const msg = (_a = update.arguments[0].messages) == null ? void 0 : _a[0]; - if (!msg) - continue; - if (!msg.messageType) { - result.author = msg.author; - result.text = msg.text; - result.detail = msg; - onProgress == null ? void 0 : onProgress(result); - } - } else if (message.type === 2) { - const response = message; - if (this._debug) { - console.log("RESPONSE", JSON.stringify(response, null, 2)); - } - const validMessages = (_b = response.item.messages) == null ? void 0 : _b.filter( - (m) => !m.messageType - ); - const lastMessage = validMessages == null ? void 0 : validMessages[(validMessages == null ? void 0 : validMessages.length) - 1]; - if (lastMessage) { - result.conversationId = response.item.conversationId; - result.conversationExpiryTime = response.item.conversationExpiryTime; - result.author = lastMessage.author; - result.text = lastMessage.text; - result.detail = lastMessage; - if (!isFulfilled) { - isFulfilled = true; - resolve(result); - } - } - } else if (message.type === 3) { - if (!isFulfilled) { - isFulfilled = true; - resolve(result); - } - cleanup(); - return; - } else { - } - } - }); - } - ); - return responseP; - } - async createConversation() { - const requestId = crypto.randomUUID(); - const cookie = this._cookie.includes(";") ? this._cookie : `_U=${this._cookie}`; - return fetch("https://www.bing.com/turing/conversation/create", { - headers: { - accept: "application/json", - "accept-language": "en-US,en;q=0.9", - "content-type": "application/json", - "sec-ch-ua": '"Not_A Brand";v="99", "Microsoft Edge";v="109", "Chromium";v="109"', - "sec-ch-ua-arch": '"x86"', - "sec-ch-ua-bitness": '"64"', - "sec-ch-ua-full-version": '"109.0.1518.78"', - "sec-ch-ua-full-version-list": '"Not_A Brand";v="99.0.0.0", "Microsoft Edge";v="109.0.1518.78", "Chromium";v="109.0.5414.120"', - "sec-ch-ua-mobile": "?0", - "sec-ch-ua-model": "", - "sec-ch-ua-platform": '"macOS"', - "sec-ch-ua-platform-version": '"12.6.0"', - "sec-fetch-dest": "empty", - "sec-fetch-mode": "cors", - "sec-fetch-site": "same-origin", - "x-edge-shopping-flag": "1", - "x-ms-client-request-id": requestId, - "x-ms-useragent": "azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/MacIntel", - 'x-forwarded-for': '1.1.1.1', - cookie - }, - referrer: "https://www.bing.com/search", - referrerPolicy: "origin-when-cross-origin", - body: null, - method: "GET", - mode: "cors", - credentials: "include", - }).then((res) => { - if (res.ok) { - return res.json(); - } else { - throw new Error( - `unexpected HTTP error createConversation ${res.status}: ${res.statusText}` - ); - } - }); - } - async createImage(message) { - // const requestId = crypto.randomUUID(); - console.log(1) - const cookie = this._cookie.includes(";") ? this._cookie : `_U=${this._cookie}`; - let res = await fetch(`https://www.bing.com/images/create?q=${message}&rt=3&FORM=GENCRE`, { - headers: { - cookie - }, - method: "GET", - mode: "cors" - }) - console.log(res.headers) - if (res.status!= 302) { - throw new Error( - `unexpected HTTP error createConversation ${res.status}: ${res.statusText}` - ); - } - console.log(2) - redirect_url=res.headers["Location"].replace("&nfy=1", "") - request_id = redirect_url.split("id=")[-1] - await fetch("https://www.bing.com"+redirect_url,{method:"GET"}) - polling_url = `https://www.bing.com/images/create/async/results/${request_id}?q=${message}` - while (true){ - res = await fetch(polling_url,{method:"GET"}) - if(res.json()!=''||res.json().indexOf("errorMessage") != -1){ - await setTimeout(()=>{console.log(123)},1000) - continue - }else{ - break - } - } - console.log(3) - image_links = res.json().match('src="([^"]+)"') - normal_image_links = [] - for(let i=0 ;i {\n const {\n invocationId = '1',\n onProgress,\n locale = 'en-US',\n market = 'en-US',\n region = 'US',\n location,\n messageType = 'Chat',\n variant = 'Balanced'\n } = opts\n\n let { conversationId, clientId, conversationSignature } = opts\n const isStartOfSession = !(\n conversationId &&\n clientId &&\n conversationSignature\n )\n\n if (isStartOfSession) {\n const conversation = await this.createConversation()\n conversationId = conversation.conversationId\n clientId = conversation.clientId\n conversationSignature = conversation.conversationSignature\n }\n\n const result: types.ChatMessage = {\n author: 'bot',\n id: crypto.randomUUID(),\n conversationId,\n clientId,\n conversationSignature,\n invocationId: `${parseInt(invocationId, 10) + 1}`,\n text: ''\n }\n\n const responseP = new Promise(\n async (resolve, reject) => {\n const chatWebsocketUrl = 'wss://sydney.bing.com/sydney/ChatHub'\n const ws = new WebSocket(chatWebsocketUrl, {\n perMessageDeflate: false,\n headers: {\n 'accept-language': 'en-US,en;q=0.9',\n 'cache-control': 'no-cache',\n pragma: 'no-cache'\n }\n })\n\n let isFulfilled = false\n\n function cleanup() {\n ws.close()\n ws.removeAllListeners()\n }\n\n ws.on('error', (error) => {\n console.warn('WebSocket error:', error)\n cleanup()\n if (!isFulfilled) {\n isFulfilled = true\n reject(new Error(`WebSocket error: ${error.toString()}`))\n }\n })\n ws.on('close', () => {\n // TODO\n })\n\n ws.on('open', () => {\n ws.send(`{\"protocol\":\"json\",\"version\":1}${terminalChar}`)\n })\n let stage = 0\n\n ws.on('message', (data) => {\n const objects = data.toString().split(terminalChar)\n\n const messages = objects\n .map((object) => {\n try {\n return JSON.parse(object)\n } catch (error) {\n return object\n }\n })\n .filter(Boolean)\n\n if (!messages.length) {\n return\n }\n\n if (stage === 0) {\n ws.send(`{\"type\":6}${terminalChar}`)\n\n const traceId = crypto.randomBytes(16).toString('hex')\n\n // example location: 'lat:47.639557;long:-122.128159;re=1000m;'\n const locationStr = location\n ? `lat:${location.lat};long:${location.lng};re=${\n location.re || '1000m'\n };`\n : undefined\n\n // Sets the correct options for the variant of the model\n const optionsSets = [\n 'nlu_direct_response_filter',\n 'deepleo',\n 'enable_debug_commands',\n 'disable_emoji_spoken_text',\n 'responsible_ai_policy_235',\n 'enablemm'\n ]\n if (variant == 'Balanced') {\n optionsSets.push('galileo')\n } else {\n optionsSets.push('clgalileo')\n if (variant == 'Creative') {\n optionsSets.push('h3imaginative')\n } else if (variant == 'Precise') {\n optionsSets.push('h3precise')\n }\n }\n const params = {\n arguments: [\n {\n source: 'cib',\n optionsSets,\n allowedMessageTypes: [\n 'Chat',\n 'InternalSearchQuery',\n 'InternalSearchResult',\n 'InternalLoaderMessage',\n 'RenderCardRequest',\n 'AdsQuery',\n 'SemanticSerp'\n ],\n sliceIds: [],\n traceId,\n isStartOfSession,\n message: {\n locale,\n market,\n region,\n location: locationStr,\n author: 'user',\n inputMethod: 'Keyboard',\n messageType,\n text\n },\n conversationSignature,\n participant: { id: clientId },\n conversationId\n }\n ],\n invocationId,\n target: 'chat',\n type: 4\n }\n\n if (this._debug) {\n console.log(chatWebsocketUrl, JSON.stringify(params, null, 2))\n }\n\n ws.send(`${JSON.stringify(params)}${terminalChar}`)\n\n ++stage\n return\n }\n\n for (const message of messages) {\n // console.log(JSON.stringify(message, null, 2))\n\n if (message.type === 1) {\n const update = message as types.ChatUpdate\n const msg = update.arguments[0].messages?.[0]\n\n if (!msg) continue\n\n // console.log('RESPONSE0', JSON.stringify(update, null, 2))\n\n if (!msg.messageType) {\n result.author = msg.author\n result.text = msg.text\n result.detail = msg\n\n onProgress?.(result)\n }\n } else if (message.type === 2) {\n const response = message as types.ChatUpdateCompleteResponse\n if (this._debug) {\n console.log('RESPONSE', JSON.stringify(response, null, 2))\n }\n const validMessages = response.item.messages?.filter(\n (m) => !m.messageType\n )\n const lastMessage = validMessages?.[validMessages?.length - 1]\n\n if (lastMessage) {\n result.conversationId = response.item.conversationId\n result.conversationExpiryTime =\n response.item.conversationExpiryTime\n\n result.author = lastMessage.author\n result.text = lastMessage.text\n result.detail = lastMessage\n\n if (!isFulfilled) {\n isFulfilled = true\n resolve(result)\n }\n }\n } else if (message.type === 3) {\n if (!isFulfilled) {\n isFulfilled = true\n resolve(result)\n }\n\n cleanup()\n return\n } else {\n // TODO: handle other message types\n // these may be for displaying \"adaptive cards\"\n // console.warn('unexpected message type', message.type, message)\n }\n }\n })\n }\n )\n\n return responseP\n }\n\n async createConversation(): Promise {\n const requestId = crypto.randomUUID()\n\n const cookie = this._cookie.includes(';')\n ? this._cookie\n : `_U=${this._cookie}`\n\n return fetch('https://www.bing.com/turing/conversation/create', {\n headers: {\n accept: 'application/json',\n 'accept-language': 'en-US,en;q=0.9',\n 'content-type': 'application/json',\n 'sec-ch-ua':\n '\"Not_A Brand\";v=\"99\", \"Microsoft Edge\";v=\"109\", \"Chromium\";v=\"109\"',\n 'sec-ch-ua-arch': '\"x86\"',\n 'sec-ch-ua-bitness': '\"64\"',\n 'sec-ch-ua-full-version': '\"109.0.1518.78\"',\n 'sec-ch-ua-full-version-list':\n '\"Not_A Brand\";v=\"99.0.0.0\", \"Microsoft Edge\";v=\"109.0.1518.78\", \"Chromium\";v=\"109.0.5414.120\"',\n 'sec-ch-ua-mobile': '?0',\n 'sec-ch-ua-model': '',\n 'sec-ch-ua-platform': '\"macOS\"',\n 'sec-ch-ua-platform-version': '\"12.6.0\"',\n 'sec-fetch-dest': 'empty',\n 'sec-fetch-mode': 'cors',\n 'sec-fetch-site': 'same-origin',\n 'x-edge-shopping-flag': '1',\n 'x-ms-client-request-id': requestId,\n 'x-ms-useragent':\n 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/MacIntel',\n cookie\n },\n referrer: 'https://www.bing.com/search',\n referrerPolicy: 'origin-when-cross-origin',\n body: null,\n method: 'GET',\n mode: 'cors',\n credentials: 'include'\n }).then((res) => {\n if (res.ok) {\n return res.json()\n } else {\n throw new Error(\n `unexpected HTTP error createConversation ${res.status}: ${res.statusText}`\n )\n }\n })\n }\n}\n","/// \n\nconst fetch = globalThis.fetch\n\nif (typeof fetch !== 'function') {\n throw new Error('Invalid environment: global fetch not defined')\n}\n\nexport { fetch }\n"],"mappings":"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","names":[]} \ No newline at end of file diff --git a/app/bing-chat/license b/app/bing-chat/license deleted file mode 100644 index 3a2c00b2e108aa7f1687f41eab5a28edcc897eff..0000000000000000000000000000000000000000 --- a/app/bing-chat/license +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023 Travis Fischer - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE 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 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/app/bing-chat/package.json b/app/bing-chat/package.json deleted file mode 100644 index 56374bc1b94b602c0dc447bd30c99ab1170ccc0e..0000000000000000000000000000000000000000 --- a/app/bing-chat/package.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "name": "bing-chat", - "version": "0.2.3", - "description": "Node.js client for the unofficial Bing Chat API.", - "author": "Travis Fischer ", - "repository": "transitive-bullshit/bing-chat", - "license": "MIT", - "type": "module", - "source": "./src/index.ts", - "types": "./build/index.d.ts", - "exports": { - ".": { - "import": "./build/index.js", - "types": "./build/index.d.ts", - "default": "./build/index.js" - } - }, - "files": [ - "build" - ], - "engines": { - "node": ">=18" - }, - "scripts": { - "build": "tsup", - "dev": "tsup --watch", - "clean": "del build", - "prebuild": "run-s clean", - "predev": "run-s clean", - "pretest": "run-s build", - "docs": "typedoc", - "prepare": "husky install", - "pre-commit": "lint-staged", - "test": "run-p test:*", - "test:prettier": "prettier '**/*.{js,jsx,ts,tsx}' --check" - }, - "dependencies": { - "ws": "^8.13.0" - }, - "devDependencies": { - "@trivago/prettier-plugin-sort-imports": "^4.1.1", - "@types/node": "^18.15.3", - "@types/uuid": "^9.0.1", - "@types/ws": "^8.5.4", - "del-cli": "^5.0.0", - "dotenv-safe": "^8.2.0", - "husky": "^8.0.2", - "lint-staged": "^13.2.0", - "npm-run-all": "^4.1.5", - "ora": "^6.1.2", - "prettier": "^2.8.4", - "tsup": "^6.6.3", - "tsx": "^3.12.5", - "typedoc": "^0.23.26", - "typedoc-plugin-markdown": "^3.13.6", - "typescript": "^4.9.3" - }, - "lint-staged": { - "*.{ts,tsx}": [ - "prettier --write" - ] - }, - "keywords": [ - "openai", - "bing", - "chat", - "search", - "sydney", - "gpt", - "gpt-3", - "gpt3", - "gpt4", - "chatbot", - "machine learning", - "conversation", - "conversational", - "ai", - "ml", - "bot" - ] -} diff --git a/app/bing-chat/readme.md b/app/bing-chat/readme.md deleted file mode 100644 index e23cb17f6ddc35cb1fb9b4f9a0ee382f5f9a1800..0000000000000000000000000000000000000000 --- a/app/bing-chat/readme.md +++ /dev/null @@ -1,109 +0,0 @@ -# Bing Chat API - -> Node.js client for the unofficial Bing Chat API. It's like ChatGPT on steroids 🔥 - -[![NPM](https://img.shields.io/npm/v/bing-chat.svg)](https://www.npmjs.com/package/bing-chat) [![Build Status](https://github.com/transitive-bullshit/bing-chat/actions/workflows/test.yml/badge.svg)](https://github.com/transitive-bullshit/bing-chat/actions/workflows/test.yml) [![MIT License](https://img.shields.io/badge/license-MIT-blue)](https://github.com/transitive-bullshit/bing-chat/blob/main/license) [![Prettier Code Formatting](https://img.shields.io/badge/code_style-prettier-brightgreen.svg)](https://prettier.io) - -- [Intro](#intro) -- [Demo](#demo) -- [Install](#install) -- [Usage](#usage) -- [Projects](#projects) -- [Compatibility](#compatibility) -- [Credit](#credit) -- [Related](#related) -- [License](#license) - -## Intro - -This package is a Node.js wrapper around Bing Chat by Microsoft. TS batteries included. ✨ - -> **Warning** -> This package is a reverse-engineered hack. I do not expect it to continue working long-term, and it is not meant for use in production. I'm building this in public, and you can follow the progress on Twitter [@transitive_bs](https://twitter.com/transitive_bs). - -## Demo - -

- Example conversation - (30s conversation demo) -

- -## Install - -```bash -npm install bing-chat -``` - -Make sure you're using `node >= 18` so `fetch` is available. - -## Usage - -**You need access to Bing Chat OR a valid cookie from someone who has access**. - -The cookie you need from Bing is the `_U` cookie (or just all of the cookies concatenated together; both will work). - -```ts -import { BingChat } from 'bing-chat' - -async function example() { - const api = new BingChat({ - cookie: process.env.BING_COOKIE - }) - - const res = await api.sendMessage('Hello World!') - console.log(res.text) -} -``` - -You can follow-up messages to continue the conversation. See `demos/demo-conversation.ts` for an example. - -Note that Bing Chat conversations expire after about 20 minutes, so they're not meant to be long-term objects. - -You can add streaming via the `onProgress` handler: - -```ts -const res = await api.sendMessage('Write a 500 word essay on frogs.', { - // print the partial response as the AI is "typing" - onProgress: (partialResponse) => console.log(partialResponse.text) -}) - -// print the full text at the end -console.log(res.text) -``` - -See `demos/demo-on-progress.ts` for a full example of streaming support. - -You can also add the the parameter `variant` to the `sendMessage` function to change the variant of the AI. The default is `Balanced`, but you can also use `Precise` or `Creative`. - -```ts -const res = await api.sendMessage('Write a 500 word essay on frogs.', { - // change the variant to 'Precise' - variant: 'Creative' -}) -``` - -## Projects - -If you create a cool integration, feel free to open a PR and add it to the list. - -## Compatibility - -- This package is ESM-only. -- This package supports `node >= 18`. -- This module assumes that `fetch` is installed globally. -- If you want to build a website using `bing-chat`, we recommend using it only from your backend API - -## Credit - -- Thanks to [waylaidwanderer](https://github.com/waylaidwanderer) and [canfam](https://github.com/canfam) for helping to reverse-engineer the API 💪 - -## Related - -- [chatgpt](https://github.com/transitive-bullshit/chatgpt-api) - Node.js client for the unofficial ChatGPT API. Same author as this package. -- [discord](https://discord.gg/v9gERj825w) - Join our discord server for hackers building on top of ChatGPT / Bing / LLMs. - -## License - -MIT © [Travis Fischer](https://transitivebullsh.it) - -If you found this project interesting, please consider [sponsoring me](https://github.com/sponsors/transitive-bullshit) or following me on twitter twitter diff --git a/app/components/button.module.scss b/app/components/button.module.scss deleted file mode 100644 index b882a0c1f85dacdfeb92c75f59bf7c7af4b68a5d..0000000000000000000000000000000000000000 --- a/app/components/button.module.scss +++ /dev/null @@ -1,60 +0,0 @@ -.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 deleted file mode 100644 index 43b699b683a98ead706475e3a8f847067be1b4c9..0000000000000000000000000000000000000000 --- a/app/components/button.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index c1b08d25c930661ad21a4505176f67d7c690f1fb..0000000000000000000000000000000000000000 --- a/app/components/home.module.scss +++ /dev/null @@ -1,448 +0,0 @@ -@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: 100vh; - --window-content-width: calc(100% - var(--sidebar-width)); - - @include container(); - - max-width: 100vw; - max-height: 100vh; - - 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: 100vh; - 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; - margin-bottom: 100px; -} - -.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 { - position: absolute; - bottom: 0px; - display: flex; - 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; - 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 deleted file mode 100644 index 5e09458237781ad869539852617d28e1f437b1a5..0000000000000000000000000000000000000000 --- a/app/components/home.tsx +++ /dev/null @@ -1,674 +0,0 @@ -"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, 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={() => removeSession(i)} - /> - ))} -
- ); -} - -function useSubmitHandler() { - const config = useChatStore((state) => state.config); - const submitKey = config.submitKey; - - const shouldSubmit = (e: KeyboardEvent) => { - if (e.key !== "Enter") 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(); - - const model = useChatStore((state) => state.config.model); - // prompt hints - const promptStore = usePromptStore(); - const [promptHints, setPromptHints] = useState([]); - const onSearch = useDebouncedCallback( - (text: string) => { - if (chatStore.config.disablePromptHint) return; - setPromptHints(promptStore.search(text)); - }, - 100, - { leading: true, trailing: true }, - ); - - const onPromptSelect = (prompt: Prompt) => { - setUserInput(prompt.content); - setPromptHints([]); - inputRef.current?.focus(); - }; - - // only search prompts when user input is short - const SEARCH_TEXT_LIMIT = 30; - const onInput = (text: string) => { - setUserInput(text); - const n = text.trim().length; - if (n === 0 || n > SEARCH_TEXT_LIMIT) { - setPromptHints([]); - } else { - onSearch(text); - } - }; - - // submit user input - const onUserSubmit = () => { - if (userInput.length <= 0) return; - setIsLoading(true); - chatStore.onUserInput(userInput, model).then(() => setIsLoading(false)); - setUserInput(""); - 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: 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, model) - .then(() => setIsLoading(false)); - return; - } - } - }; - - // for auto-scroll - const latestMessageRef = useRef(null); - - // wont scroll while hovering messages - const [autoScroll, setAutoScroll] = useState(false); - - // preview messages - const messages = (session.messages as RenderMessage[]) - .concat( - isLoading - ? [ - { - role: "assistant", - content: "……", - date: new Date().toLocaleString(), - preview: true, - }, - ] - : [], - ) - .concat( - userInput.length > 0 - ? [ - { - role: "user", - content: userInput, - date: new Date().toLocaleString(), - preview: true, - }, - ] - : [], - ); - - // auto scroll - useLayoutEffect(() => { - setTimeout(() => { - const dom = latestMessageRef.current; - if (dom && !isIOS() && autoScroll) { - dom.scrollIntoView({ - behavior: "smooth", - block: "end", - }); - } - }, 500); - }); - - return ( -
-
-
-
- {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 ? ( - - ) : message.content.indexOf("https") != 0 ? ( -
onRightClick(e, message)} - onDoubleClickCapture={() => setUserInput(message.content)} - > - -
- ) : ( -
- {/* eslint-disable-next-line @next/next/no-img-element */} - 图片 -
- )} -
- {!isUser && !message.preview && ( -
-
- {message.date.toLocaleString()} -
-
- )} -
-
- ); - })} -
- - -
-
- -
- -
-