Compare commits

...

35 Commits

Author SHA1 Message Date
4b95f23867 no message 2024-05-11 11:59:51 +08:00
9bae199f05 no message 2024-05-10 18:35:11 +08:00
c3446eeebb no message 2024-05-10 18:09:18 +08:00
7def5ea6bf no message 2024-04-09 17:33:39 +08:00
cb8dfa6fd1 no message 2024-02-25 21:00:10 +08:00
3a1c8c1e6a no message 2024-02-25 20:41:38 +08:00
ed72e9e439 no message 2024-02-25 19:54:03 +08:00
68dfed3453 no message 2024-02-25 10:53:40 +08:00
2990656d07 no message 2024-02-25 00:01:23 +08:00
2b7e8f1740 no message 2024-02-24 20:02:02 +08:00
42e3365ed5 名字写错 2024-02-24 17:52:38 +08:00
74d1b76a74 Merge pull request '增加窗口尺寸动画。' (#2) from singlexyz/ChatGPT-Next-Web:main into main
Reviewed-on: https://x-mo.cn:9009/XiaoMo/ChatGPT-Next-Web/pulls/2
2024-02-24 09:47:24 +00:00
572c627db3 增加窗口尺寸动画。 2024-02-24 17:03:18 +08:00
ca6205e6dc no message 2024-02-24 11:02:41 +08:00
7a30b73bce no message 2024-02-24 10:39:52 +08:00
a1e683d0c5 no message 2024-02-24 10:36:48 +08:00
f6ba744fd8 no message 2024-02-24 09:53:44 +08:00
93e30f2fdb .... 2024-02-24 00:37:31 +08:00
56a6015ed4 no message 2024-02-24 00:13:03 +08:00
7f859e3a78 Merge pull request 'GPT Logo 点击9次有彩蛋。' (#1) from singlexyz/ChatGPT-Next-Web:main into main
Reviewed-on: https://x-mo.cn:9009/XiaoMo/ChatGPT-Next-Web/pulls/1
2024-02-23 14:51:19 +00:00
74593a955c GPT Logo 点击9次有彩蛋。 2024-02-23 22:24:06 +08:00
7eff84bf0b no message 2024-02-23 15:50:54 +08:00
H0llyW00dzZ
e756506c18
[Cherry Pick] Improve Github Issue Template (#4041)
* Improve Github Issue Template

- [+] feat(issue templates): update issue templates from markdown to form schema
- [+] feat(issue templates): translate issue templates to Chinese
- [+] remove(issue templates): delete old markdown issue templates

* chore: remove Chinese template issue temporarily

---------

Co-authored-by: Fred <fred@nextchat.dev>
2024-02-20 18:11:02 +08:00
Qiying Wang
fd67f980a5
Fix temperature range (#4083) 2024-02-20 18:05:17 +08:00
TheRam_
e2da3406d2
Add vision support (#4076) 2024-02-20 18:04:32 +08:00
Ikko Eltociear Ashimine
05b6d989b6
chore: fix typo in next.config.mjs (#4072)
verison -> version
2024-02-20 17:59:59 +08:00
H0llyW00dzZ
1d6ee64e1d
[Cherry Pick] Fix [UI/UX] [Front End] Settings Page (#4032)
* Fix [UI/UX] [Locales] Correct Spelling

- [+] fix(locales): correct spelling and improve wording in cn.ts and en.ts locale files

* Fix [UI/UX] [Front End] Settings Page

- [+] fix(settings.tsx): correct typo in ApiVerion to ApiVersion
- [+] refactor(settings.tsx): switch Azure.ApiKey to Google.ApiKey in ListItem title and subTitle

* Fix [UI/UX] [Locales] [SK] Correct Typo

- [+] fix(sk.ts): correct typo in ApiVersion key in Slovak locale file
2024-02-12 20:36:52 +08:00
fred-bf
bfefb99192
chore: update tauri dependencies (#4018)
* feat: bump version

* feat: bump version

* chore: update tauri dependencies
2024-02-07 14:12:04 +08:00
Anivie Michaelis
47ae874e4d
fix: add support to http scheme. (#3985)
Co-authored-by: fred-bf <157469842+fred-bf@users.noreply.github.com>
2024-02-07 13:48:28 +08:00
fred-bf
d74f636558
Fix/gemini app endpoint (#4017)
* fix: support custom api endpoint

* fix: attach api key to google gemini
2024-02-07 13:46:52 +08:00
fred-bf
b8f0822214
fix: support custom api endpoint (#4016) 2024-02-07 13:40:30 +08:00
fred-bf
0869455612
feat: bump version (#4015)
* feat: bump version

* feat: bump version
2024-02-07 13:38:02 +08:00
fred-bf
bca74241e6
fix: fix gemini issue when using app (#4013)
* chore: update path

* fix: fix google auth logic

* fix: not using header authorization for google api

* chore: revert to allow stream
2024-02-07 13:17:11 +08:00
fred-bf
9d5801fb5f
fix: avoiding not operation for custom models (#4010) 2024-02-07 10:31:49 +08:00
H0llyW00dzZ
462a88ae82
Fix [CI/CD] [Vercel] Deploy Preview (#4005)
- [+] feat(.github/workflows/deploy_preview.yml): add 'reopened' event trigger
2024-02-06 17:20:12 +08:00
95 changed files with 12985 additions and 3925 deletions

View File

@ -1,43 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: "[Bug] "
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Deployment**
- [ ] Docker
- [ ] Vercel
- [ ] Server
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional Logs**
Add any logs about the problem here.

View File

@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[Feature] "
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@ -1,24 +0,0 @@
---
name: 功能建议
about: 请告诉我们你的灵光一闪
title: "[Feature] "
labels: ''
assignees: ''
---
> 为了提高交流效率,我们设立了官方 QQ 群和 QQ 频道,如果你在使用或者搭建过程中遇到了任何问题,请先第一时间加群或者频道咨询解决,除非是可以稳定复现的 Bug 或者较为有创意的功能建议,否则请不要随意往 Issue 区发送低质无意义帖子。
> [点击加入官方群聊](https://github.com/Yidadaa/ChatGPT-Next-Web/discussions/1724)
**这个功能与现有的问题有关吗?**
如果有关,请在此列出链接或者描述问题。
**你想要什么功能或者有什么建议?**
尽管告诉我们。
**有没有可以参考的同类竞品?**
可以给出参考产品的链接或者截图。
**其他信息**
可以说说你的其他考虑。

View File

@ -1,36 +0,0 @@
---
name: 反馈问题
about: 请告诉我们你遇到的问题
title: "[Bug] "
labels: ''
assignees: ''
---
> 为了提高交流效率,我们设立了官方 QQ 群和 QQ 频道,如果你在使用或者搭建过程中遇到了任何问题,请先第一时间加群或者频道咨询解决,除非是可以稳定复现的 Bug 或者较为有创意的功能建议,否则请不要随意往 Issue 区发送低质无意义帖子。
> [点击加入官方群聊](https://github.com/Yidadaa/ChatGPT-Next-Web/discussions/1724)
**反馈须知**
⚠️ 注意:不遵循此模板的任何帖子都会被立即关闭,如果没有提供下方的信息,我们无法定位你的问题。
请在下方中括号内输入 x 来表示你已经知晓相关内容。
- [ ] 我确认已经在 [常见问题](https://github.com/Yidadaa/ChatGPT-Next-Web/blob/main/docs/faq-cn.md) 中搜索了此次反馈的问题,没有找到解答;
- [ ] 我确认已经在 [Issues](https://github.com/Yidadaa/ChatGPT-Next-Web/issues) 列表(包括已经 Close 的)中搜索了此次反馈的问题,没有找到解答。
- [ ] 我确认已经在 [Vercel 使用教程](https://github.com/Yidadaa/ChatGPT-Next-Web/blob/main/docs/vercel-cn.md) 中搜索了此次反馈的问题,没有找到解答。
**描述问题**
请在此描述你遇到了什么问题。
**如何复现**
请告诉我们你是通过什么操作触发的该问题。
**截图**
请在此提供控制台截图、屏幕截图或者服务端的 log 截图。
**一些必要的信息**
- 系统:[比如 windows 10/ macos 12/ linux / android 11 / ios 16]
- 浏览器: [比如 chrome, safari]
- 版本: [填写设置页面的版本号]
- 部署方式:[比如 vercel、docker 或者服务器部署]

View File

@ -1,11 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "npm" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"

View File

@ -1,110 +0,0 @@
name: Release App
on:
workflow_dispatch:
release:
types: [published]
jobs:
create-release:
permissions:
contents: write
runs-on: ubuntu-latest
outputs:
release_id: ${{ steps.create-release.outputs.result }}
steps:
- uses: actions/checkout@v3
- name: setup node
uses: actions/setup-node@v3
with:
node-version: 18
- name: get version
run: echo "PACKAGE_VERSION=$(node -p "require('./src-tauri/tauri.conf.json').package.version")" >> $GITHUB_ENV
- name: create release
id: create-release
uses: actions/github-script@v6
with:
script: |
const { data } = await github.rest.repos.getLatestRelease({
owner: context.repo.owner,
repo: context.repo.repo,
})
return data.id
build-tauri:
needs: create-release
permissions:
contents: write
strategy:
fail-fast: false
matrix:
config:
- os: ubuntu-latest
arch: x86_64
rust_target: x86_64-unknown-linux-gnu
- os: macos-latest
arch: aarch64
rust_target: x86_64-apple-darwin,aarch64-apple-darwin
- os: windows-latest
arch: x86_64
rust_target: x86_64-pc-windows-msvc
runs-on: ${{ matrix.config.os }}
steps:
- uses: actions/checkout@v3
- name: setup node
uses: actions/setup-node@v3
with:
node-version: 18
cache: 'yarn'
- name: install Rust stable
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.config.rust_target }}
- uses: Swatinem/rust-cache@v2
with:
key: ${{ matrix.config.os }}
- name: install dependencies (ubuntu only)
if: matrix.config.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf
- name: install frontend dependencies
run: yarn install # change this to npm or pnpm depending on which one you use
- uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
with:
releaseId: ${{ needs.create-release.outputs.release_id }}
args: ${{ matrix.config.os == 'macos-latest' && '--target universal-apple-darwin' || '' }}
publish-release:
permissions:
contents: write
runs-on: ubuntu-latest
needs: [create-release, build-tauri]
steps:
- name: publish release
id: publish-release
uses: actions/github-script@v6
env:
release_id: ${{ needs.create-release.outputs.release_id }}
with:
script: |
github.rest.repos.updateRelease({
owner: context.repo.owner,
repo: context.repo.repo,
release_id: process.env.release_id,
draft: false,
prerelease: false
})

View File

@ -1,83 +0,0 @@
name: VercelPreviewDeployment
on:
pull_request_target:
types:
- opened
- synchronize
env:
VERCEL_TEAM: ${{ secrets.VERCEL_TEAM }}
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
VERCEL_PR_DOMAIN_SUFFIX: ${{ secrets.VERCEL_PR_DOMAIN_SUFFIX }}
permissions:
contents: read
statuses: write
pull-requests: write
jobs:
deploy-preview:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Extract branch name
shell: bash
run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> "$GITHUB_OUTPUT"
id: extract_branch
- name: Hash branch name
uses: pplanel/hash-calculator-action@v1.3.1
id: hash_branch
with:
input: ${{ steps.extract_branch.outputs.branch }}
method: MD5
- name: Set Environment Variables
id: set_env
if: github.event_name == 'pull_request_target'
run: |
echo "VERCEL_ALIAS_DOMAIN=${{ github.event.pull_request.number }}-${{ github.workflow }}.${VERCEL_PR_DOMAIN_SUFFIX}" >> $GITHUB_OUTPUT
- name: Install Vercel CLI
run: npm install --global vercel@latest
- name: Cache dependencies
uses: actions/cache@v2
id: cache-npm
with:
path: ~/.npm
key: npm-${{ hashFiles('package-lock.json') }}
restore-keys: npm-
- name: Pull Vercel Environment Information
run: vercel pull --yes --environment=preview --token=${VERCEL_TOKEN}
- name: Deploy Project Artifacts to Vercel
id: vercel
env:
META_TAG: ${{ steps.hash_branch.outputs.digest }}-${{ github.run_number }}-${{ github.run_attempt}}
run: |
set -e
vercel pull --yes --environment=preview --token=${VERCEL_TOKEN}
vercel build --token=${VERCEL_TOKEN}
vercel deploy --prebuilt --archive=tgz --token=${VERCEL_TOKEN} --meta base_hash=${{ env.META_TAG }}
DEFAULT_URL=$(vercel ls --token=${VERCEL_TOKEN} --meta base_hash=${{ env.META_TAG }})
ALIAS_URL=$(vercel alias set ${DEFAULT_URL} ${{ steps.set_env.outputs.VERCEL_ALIAS_DOMAIN }} --token=${VERCEL_TOKEN} --scope ${VERCEL_TEAM}| awk '{print $3}')
echo "New preview URL: ${DEFAULT_URL}"
echo "New alias URL: ${ALIAS_URL}"
echo "VERCEL_URL=${ALIAS_URL}" >> "$GITHUB_OUTPUT"
- uses: mshick/add-pr-comment@v2
with:
message: |
Your build has completed!
[Preview deployment](${{ steps.vercel.outputs.VERCEL_URL }})

View File

@ -1,52 +0,0 @@
name: Publish Docker image
on:
workflow_dispatch:
release:
types: [published]
jobs:
push_to_registry:
name: Push Docker image to Docker Hub
runs-on: ubuntu-latest
steps:
-
name: Check out the repo
uses: actions/checkout@v3
-
name: Log in to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
-
name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v4
with:
images: yidadaa/chatgpt-next-web
tags: |
type=raw,value=latest
type=ref,event=tag
-
name: Set up QEMU
uses: docker/setup-qemu-action@v2
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
-
name: Build and push Docker image
uses: docker/build-push-action@v4
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max

View File

@ -1,15 +0,0 @@
name: Issue Translator
on:
issue_comment:
types: [created]
issues:
types: [opened]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: usthe/issues-translate-action@v2.7
with:
IS_MODIFY_TITLE: false
CUSTOM_BOT_NOTE: Bot detected the issue body's language is not English, translate it automatically.

View File

@ -1,40 +0,0 @@
name: Removedeploypreview
permissions:
contents: read
statuses: write
pull-requests: write
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
on:
pull_request_target:
types:
- closed
jobs:
delete-deployments:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Extract branch name
shell: bash
run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> $GITHUB_OUTPUT
id: extract_branch
- name: Hash branch name
uses: pplanel/hash-calculator-action@v1.3.1
id: hash_branch
with:
input: ${{ steps.extract_branch.outputs.branch }}
method: MD5
- name: Call the delete-deployment-preview.sh script
env:
META_TAG: ${{ steps.hash_branch.outputs.digest }}
run: |
bash ./scripts/delete-deployment-preview.sh

View File

@ -1,40 +0,0 @@
name: Upstream Sync
permissions:
contents: write
on:
schedule:
- cron: "0 0 * * *" # every day
workflow_dispatch:
jobs:
sync_latest_from_upstream:
name: Sync latest commits from upstream repo
runs-on: ubuntu-latest
if: ${{ github.event.repository.fork }}
steps:
# Step 1: run a standard checkout action
- name: Checkout target repo
uses: actions/checkout@v3
# Step 2: run the sync action
- name: Sync upstream changes
id: sync
uses: aormsby/Fork-Sync-With-Upstream-action@v3.4
with:
upstream_sync_repo: ChatGPTNextWeb/ChatGPT-Next-Web
upstream_sync_branch: main
target_sync_branch: main
target_repo_token: ${{ secrets.GITHUB_TOKEN }} # automatically generated, no need to set
# Set test_mode true to run tests instead of the true action!!
test_mode: false
- name: Sync check
if: failure()
run: |
echo "[Error] 由于上游仓库的 workflow 文件变更,导致 GitHub 自动暂停了本次自动更新,你需要手动 Sync Fork 一次详细教程请查看https://github.com/Yidadaa/ChatGPT-Next-Web/blob/main/README_CN.md#%E6%89%93%E5%BC%80%E8%87%AA%E5%8A%A8%E6%9B%B4%E6%96%B0"
echo "[Error] Due to a change in the workflow file of the upstream repository, GitHub has automatically suspended the scheduled automatic update. You need to manually sync your fork. Please refer to the detailed tutorial for instructions: https://github.com/Yidadaa/ChatGPT-Next-Web#enable-automatic-updates"
exit 1

View File

@ -1,4 +0,0 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged

View File

@ -1,128 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
flynn.zhang@foxmail.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

View File

@ -1,64 +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 ./
RUN yarn config set registry 'https://registry.npmmirror.com/'
RUN yarn install
FROM base AS builder
RUN apk update && apk add --no-cache git
ENV OPENAI_API_KEY=""
ENV GOOGLE_API_KEY=""
ENV CODE=""
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN yarn build
FROM base AS runner
WORKDIR /app
RUN apk add proxychains-ng
ENV PROXY_URL=""
ENV OPENAI_API_KEY=""
ENV GOOGLE_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 if [ -n "$PROXY_URL" ]; then \
export HOSTNAME="127.0.0.1"; \
protocol=$(echo $PROXY_URL | cut -d: -f1); \
host=$(echo $PROXY_URL | cut -d/ -f3 | cut -d: -f1); \
port=$(echo $PROXY_URL | cut -d: -f3); \
conf=/etc/proxychains.conf; \
echo "strict_chain" > $conf; \
echo "proxy_dns" >> $conf; \
echo "remote_dns_subnet 224" >> $conf; \
echo "tcp_read_time_out 15000" >> $conf; \
echo "tcp_connect_time_out 8000" >> $conf; \
echo "localnet 127.0.0.0/255.0.0.0" >> $conf; \
echo "localnet ::1/128" >> $conf; \
echo "[ProxyList]" >> $conf; \
echo "$protocol $host $port" >> $conf; \
cat /etc/proxychains.conf; \
proxychains -f $conf node server.js; \
else \
node server.js; \
fi

21
LICENSE
View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2023 Zhang Yifei
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.

View File

@ -14,9 +14,17 @@ export type MessageRole = (typeof ROLES)[number];
export const Models = ["gpt-3.5-turbo", "gpt-4"] as const;
export type ChatModel = ModelType;
export interface MultimodalContent {
type: "text" | "image_url";
text?: string;
image_url?: {
url: string;
};
}
export interface RequestMessage {
role: MessageRole;
content: string;
content: string | MultimodalContent[];
}
export interface LLMConfig {
@ -108,8 +116,7 @@ export class ClientApi {
.concat([
{
from: "human",
value:
"Share from [NextChat]: https://github.com/Yidadaa/ChatGPT-Next-Web",
value: "Share from [GrerIngChat]: https://gtering.com",
},
]);
// 敬告二开开发者们,为了开源大模型的发展,请不要修改上述消息,此消息用于后续数据清洗使用
@ -144,10 +151,10 @@ export function getHeaders() {
const headers: Record<string, string> = {
"Content-Type": "application/json",
"x-requested-with": "XMLHttpRequest",
"Accept": "application/json",
Accept: "application/json",
};
const modelConfig = useChatStore.getState().currentSession().mask.modelConfig;
const isGoogle = modelConfig.model === "gemini-pro";
const isGoogle = modelConfig.model.startsWith("gemini");
const isAzure = accessStore.provider === ServiceProvider.Azure;
const authHeader = isAzure ? "api-key" : "Authorization";
const apiKey = isGoogle
@ -155,10 +162,12 @@ export function getHeaders() {
: isAzure
? accessStore.azureApiKey
: accessStore.openaiApiKey;
const clientConfig = getClientConfig();
const makeBearer = (s: string) => `${isAzure ? "" : "Bearer "}${s.trim()}`;
const validString = (x: string) => x && x.length > 0;
// when using google api in app, not set auth header
if (!(isGoogle && clientConfig?.isApp)) {
// use user's api key first
if (validString(apiKey)) {
headers[authHeader] = makeBearer(apiKey);
@ -170,6 +179,7 @@ export function getHeaders() {
ACCESS_CODE_PREFIX + accessStore.accessCode,
);
}
}
return headers;
}

View File

@ -1,15 +1,14 @@
import { Google, REQUEST_TIMEOUT_MS } from "@/app/constant";
import { ChatOptions, getHeaders, LLMApi, LLMModel, LLMUsage } from "../api";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import {
EventStreamContentType,
fetchEventSource,
} from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client";
import Locale from "../../locales";
import { getServerSideConfig } from "@/app/config/server";
import de from "@/app/locales/de";
import { DEFAULT_API_HOST } from "@/app/constant";
import {
getMessageTextContent,
getMessageImages,
isVisionModel,
} from "@/app/utils";
export class GeminiProApi implements LLMApi {
extractMessage(res: any) {
console.log("[Response] gemini-pro response: ", res);
@ -21,11 +20,34 @@ export class GeminiProApi implements LLMApi {
);
}
async chat(options: ChatOptions): Promise<void> {
const apiClient = this;
const messages = options.messages.map((v) => ({
// const apiClient = this;
const visionModel = isVisionModel(options.config.model);
let multimodal = false;
const messages = options.messages.map((v) => {
let parts: any[] = [{ text: getMessageTextContent(v) }];
if (visionModel) {
const images = getMessageImages(v);
if (images.length > 0) {
multimodal = true;
parts = parts.concat(
images.map((image) => {
const imageType = image.split(";")[0].split(":")[1];
const imageData = image.split(",")[1];
return {
inline_data: {
mime_type: imageType,
data: imageData,
},
};
}),
);
}
}
return {
role: v.role.replace("assistant", "model").replace("system", "user"),
parts: [{ text: v.content }],
}));
parts: parts,
};
});
// google requires that role in neighboring messages must not be the same
for (let i = 0; i < messages.length - 1; ) {
@ -40,7 +62,9 @@ export class GeminiProApi implements LLMApi {
i++;
}
}
// if (visionModel && messages.length > 1) {
// options.onError?.(new Error("Multiturn chat is not enabled for models/gemini-pro-vision"));
// }
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
@ -79,13 +103,30 @@ export class GeminiProApi implements LLMApi {
],
};
console.log("[Request] google payload: ", requestPayload);
const accessStore = useAccessStore.getState();
let baseUrl = accessStore.googleUrl;
const isApp = !!getClientConfig()?.isApp;
const shouldStream = !!options.config.stream;
let shouldStream = !!options.config.stream;
const controller = new AbortController();
options.onController?.(controller);
try {
const chatPath = this.path(Google.ChatPath);
let googleChatPath = visionModel
? Google.VisionChatPath
: Google.ChatPath;
let chatPath = this.path(googleChatPath);
// let baseUrl = accessStore.googleUrl;
if (!baseUrl) {
baseUrl = isApp
? DEFAULT_API_HOST + "/api/proxy/google/" + googleChatPath
: chatPath;
}
if (isApp) {
baseUrl += `?key=${accessStore.googleApiKey}`;
}
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
@ -101,10 +142,6 @@ export class GeminiProApi implements LLMApi {
if (shouldStream) {
let responseText = "";
let remainText = "";
let streamChatPath = chatPath.replace(
"generateContent",
"streamGenerateContent",
);
let finished = false;
let existingTexts: string[] = [];
@ -134,7 +171,11 @@ export class GeminiProApi implements LLMApi {
// start animaion
animateResponseText();
fetch(streamChatPath, chatPayload)
fetch(
baseUrl.replace("generateContent", "streamGenerateContent"),
chatPayload,
)
.then((response) => {
const reader = response?.body?.getReader();
const decoder = new TextDecoder();
@ -145,6 +186,19 @@ export class GeminiProApi implements LLMApi {
value,
}): Promise<any> {
if (done) {
if (response.status !== 200) {
try {
let data = JSON.parse(ensureProperEnding(partialData));
if (data && data[0].error) {
options.onError?.(new Error(data[0].error.message));
} else {
options.onError?.(new Error("Request failed"));
}
} catch (_) {
options.onError?.(new Error("Request failed"));
}
}
console.log("Stream complete");
// options.onFinish(responseText + remainText);
finished = true;
@ -185,11 +239,9 @@ export class GeminiProApi implements LLMApi {
console.error("Error:", error);
});
} else {
const res = await fetch(chatPath, chatPayload);
const res = await fetch(baseUrl, chatPayload);
clearTimeout(requestTimeoutId);
const resJson = await res.json();
if (resJson?.promptFeedback?.blockReason) {
// being blocked
options.onError?.(

View File

@ -1,3 +1,4 @@
"use client";
import {
ApiPath,
DEFAULT_API_HOST,
@ -8,7 +9,14 @@ import {
} from "@/app/constant";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import { ChatOptions, getHeaders, LLMApi, LLMModel, LLMUsage } from "../api";
import {
ChatOptions,
getHeaders,
LLMApi,
LLMModel,
LLMUsage,
MultimodalContent,
} from "../api";
import Locale from "../../locales";
import {
EventStreamContentType,
@ -17,6 +25,11 @@ import {
import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client";
import { makeAzurePath } from "@/app/azure";
import {
getMessageTextContent,
getMessageImages,
isVisionModel,
} from "@/app/utils";
export interface OpenAIListModelResponse {
object: string;
@ -45,7 +58,9 @@ export class ChatGPTApi implements LLMApi {
if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
baseUrl = isApp ? DEFAULT_API_HOST : ApiPath.OpenAI;
baseUrl = isApp
? DEFAULT_API_HOST + "/proxy" + ApiPath.OpenAI
: ApiPath.OpenAI;
}
if (baseUrl.endsWith("/")) {
@ -59,6 +74,8 @@ export class ChatGPTApi implements LLMApi {
path = makeAzurePath(path, accessStore.azureApiVersion);
}
console.log("[Proxy Endpoint] ", baseUrl, path);
return [baseUrl, path].join("/");
}
@ -67,9 +84,10 @@ export class ChatGPTApi implements LLMApi {
}
async chat(options: ChatOptions) {
const visionModel = isVisionModel(options.config.model);
const messages = options.messages.map((v) => ({
role: v.role,
content: v.content,
content: visionModel ? v.content : getMessageTextContent(v),
}));
const modelConfig = {

View File

@ -1,5 +1,47 @@
@import "../styles/animation.scss";
.attach-images {
position: absolute;
left: 30px;
bottom: 32px;
display: flex;
}
.attach-image {
cursor: default;
width: 64px;
height: 64px;
border: rgba($color: #888, $alpha: 0.2) 1px solid;
border-radius: 5px;
margin-right: 10px;
background-size: cover;
background-position: center;
background-color: var(--white);
.attach-image-mask {
width: 100%;
height: 100%;
opacity: 0;
transition: all ease 0.2s;
}
.attach-image-mask:hover {
opacity: 1;
}
.delete-image {
width: 24px;
height: 24px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
border-radius: 5px;
float: right;
background-color: var(--white);
}
}
.chat-input-actions {
display: flex;
flex-wrap: wrap;
@ -189,12 +231,10 @@
animation: slide-in ease 0.3s;
$linear: linear-gradient(
to right,
$linear: linear-gradient(to right,
rgba(0, 0, 0, 0),
rgba(0, 0, 0, 1),
rgba(0, 0, 0, 0)
);
rgba(0, 0, 0, 0));
mask-image: $linear;
@mixin show {
@ -349,6 +389,7 @@
padding: 7px;
}
}
/* Specific styles for iOS devices */
@media screen and (max-device-width: 812px) and (-webkit-min-device-pixel-ratio: 2) {
@supports (-webkit-touch-callout: none) {
@ -381,6 +422,64 @@
transition: all ease 0.3s;
}
.chat-message-item-image {
width: 100%;
margin-top: 10px;
}
.chat-message-item-images {
width: 100%;
display: grid;
justify-content: left;
grid-gap: 10px;
grid-template-columns: repeat(var(--image-count), auto);
margin-top: 10px;
}
.chat-message-item-image-multi {
object-fit: cover;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
.chat-message-item-image,
.chat-message-item-image-multi {
box-sizing: border-box;
border-radius: 10px;
border: rgba($color: #888, $alpha: 0.2) 1px solid;
}
@media only screen and (max-width: 600px) {
$calc-image-width: calc(100vw/3*2/var(--image-count));
.chat-message-item-image-multi {
width: $calc-image-width;
height: $calc-image-width;
}
.chat-message-item-image {
max-width: calc(100vw/3*2);
}
}
@media screen and (min-width: 600px) {
$max-image-width: calc(calc(1200px - var(--sidebar-width))/3*2/var(--image-count));
$image-width: calc(calc(var(--window-width) - var(--sidebar-width))/3*2/var(--image-count));
.chat-message-item-image-multi {
width: $image-width;
height: $image-width;
max-width: $max-image-width;
max-height: $max-image-width;
}
.chat-message-item-image {
max-width: calc(calc(1200px - var(--sidebar-width))/3*2);
}
}
.chat-message-action-date {
font-size: 12px;
opacity: 0.2;
@ -460,6 +559,7 @@
@include single-line();
}
.hint-content {
font-size: 12px;
@ -474,15 +574,26 @@
}
.chat-input-panel-inner {
cursor: text;
display: flex;
flex: 1;
border-radius: 10px;
border: var(--border-in-light);
}
.chat-input-panel-inner-attach {
padding-bottom: 80px;
}
.chat-input-panel-inner:has(.chat-input:focus) {
border: 1px solid var(--primary);
}
.chat-input {
height: 100%;
width: 100%;
border-radius: 10px;
border: var(--border-in-light);
border: none;
box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.03);
background-color: var(--white);
color: var(--black);
@ -494,9 +605,7 @@
min-height: 68px;
}
.chat-input:focus {
border: 1px solid var(--primary);
}
.chat-input:focus {}
.chat-input-send {
background-color: var(--primary);

View File

@ -15,6 +15,7 @@ import ExportIcon from "../icons/share.svg";
import ReturnIcon from "../icons/return.svg";
import CopyIcon from "../icons/copy.svg";
import LoadingIcon from "../icons/three-dots.svg";
import LoadingButtonIcon from "../icons/loading.svg";
import PromptIcon from "../icons/prompt.svg";
import MaskIcon from "../icons/mask.svg";
import MaxIcon from "../icons/max.svg";
@ -27,6 +28,7 @@ import PinIcon from "../icons/pin.svg";
import EditIcon from "../icons/rename.svg";
import ConfirmIcon from "../icons/confirm.svg";
import CancelIcon from "../icons/cancel.svg";
import ImageIcon from "../icons/image.svg";
import LightIcon from "../icons/light.svg";
import DarkIcon from "../icons/dark.svg";
@ -53,6 +55,10 @@ import {
selectOrCopy,
autoGrowTextArea,
useMobileScreen,
getMessageTextContent,
getMessageImages,
isVisionModel,
compressImage,
} from "../utils";
import dynamic from "next/dynamic";
@ -89,6 +95,7 @@ import { prettyObject } from "../utils/format";
import { ExportMessageModal } from "./exporter";
import { getClientConfig } from "../config/client";
import { useAllModels } from "../utils/hooks";
import { MultimodalContent } from "../client/api";
const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
loading: () => <LoadingIcon />,
@ -406,10 +413,14 @@ function useScrollToBottom() {
}
export function ChatActions(props: {
uploadImage: () => void;
setAttachImages: (images: string[]) => void;
setUploading: (uploading: boolean) => void;
showPromptModal: () => void;
scrollToBottom: () => void;
showPromptHints: () => void;
hitBottom: boolean;
uploading: boolean;
}) {
const config = useAppConfig();
const navigate = useNavigate();
@ -437,8 +448,16 @@ export function ChatActions(props: {
[allModels],
);
const [showModelSelector, setShowModelSelector] = useState(false);
const [showUploadImage, setShowUploadImage] = useState(false);
useEffect(() => {
const show = isVisionModel(currentModel);
setShowUploadImage(show);
if (!show) {
props.setAttachImages([]);
props.setUploading(false);
}
// if current model is not available
// switch to first available model
const isUnavaliableModel = !models.some((m) => m.name === currentModel);
@ -475,6 +494,13 @@ export function ChatActions(props: {
/>
)}
{showUploadImage && (
<ChatAction
onClick={props.uploadImage}
text={Locale.Chat.InputActions.UploadImage}
icon={props.uploading ? <LoadingButtonIcon /> : <ImageIcon />}
/>
)}
<ChatAction
onClick={nextTheme}
text={Locale.Chat.InputActions.Theme[theme]}
@ -491,12 +517,15 @@ export function ChatActions(props: {
}
/>
{useAccessStore().openaiApiKey && (
<ChatAction
onClick={props.showPromptHints}
text={Locale.Chat.InputActions.Prompt}
icon={<PromptIcon />}
/>
)}
{useAccessStore().openaiApiKey && (
<ChatAction
onClick={() => {
navigate(Path.Masks);
@ -504,6 +533,7 @@ export function ChatActions(props: {
text={Locale.Chat.InputActions.Masks}
icon={<MaskIcon />}
/>
)}
<ChatAction
text={Locale.Chat.InputActions.Clear}
@ -610,6 +640,14 @@ export function EditMessageModal(props: { onClose: () => void }) {
);
}
export function DeleteImageButton(props: { deleteImage: () => void }) {
return (
<div className={styles["delete-image"]} onClick={props.deleteImage}>
<DeleteIcon />
</div>
);
}
function _Chat() {
type RenderMessage = ChatMessage & { preview?: boolean };
@ -628,6 +666,8 @@ function _Chat() {
const [hitBottom, setHitBottom] = useState(true);
const isMobileScreen = useMobileScreen();
const navigate = useNavigate();
const [attachImages, setAttachImages] = useState<string[]>([]);
const [uploading, setUploading] = useState(false);
// prompt hints
const promptStore = usePromptStore();
@ -696,6 +736,12 @@ function _Chat() {
};
const doSubmit = (userInput: string) => {
if (!accessStore.openaiApiKey) {
window.location.href =
"https://passport.gter.net/?referer=https://app.gter.net/ai/login?token={token}#/scanLogin)";
return true;
}
if (userInput.trim() === "") return;
const matchCommand = chatCommands.match(userInput);
if (matchCommand.matched) {
@ -705,7 +751,10 @@ function _Chat() {
return;
}
setIsLoading(true);
chatStore.onUserInput(userInput).then(() => setIsLoading(false));
chatStore
.onUserInput(userInput, attachImages)
.then(() => setIsLoading(false));
setAttachImages([]);
localStorage.setItem(LAST_INPUT_KEY, userInput);
setUserInput("");
setPromptHints([]);
@ -783,9 +832,9 @@ function _Chat() {
};
const onRightClick = (e: any, message: ChatMessage) => {
// copy to clipboard
if (selectOrCopy(e.currentTarget, message.content)) {
if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
if (userInput.length === 0) {
setUserInput(message.content);
setUserInput(getMessageTextContent(message));
}
e.preventDefault();
@ -853,7 +902,9 @@ function _Chat() {
// resend the message
setIsLoading(true);
chatStore.onUserInput(userMessage.content).then(() => setIsLoading(false));
const textContent = getMessageTextContent(userMessage);
const images = getMessageImages(userMessage);
chatStore.onUserInput(textContent, images).then(() => setIsLoading(false));
inputRef.current?.focus();
};
@ -1002,15 +1053,25 @@ function _Chat() {
const payload = JSON.parse(text) as {
key?: string;
url?: string;
uin?: number;
uid?: number;
};
console.log("[Command] got settings from url: ", payload);
if (
accessStore.openaiApiKey == payload.key &&
accessStore.openaiUrl == payload.url
) {
return true;
}
console.log("[Command] got settings from url: ", payload);
if (payload.key || payload.url) {
showConfirm(
Locale.URLCommand.Settings +
`\n${JSON.stringify(payload, null, 4)}`,
).then((res) => {
// var messages = Locale.URLCommand.Settings + `\n${JSON.stringify(payload, null, 4)}`;
var messages =
"检测到已登录寄托账号(UID:" +
(payload.uin || payload.uid) +
"),请确定是否继续登录?";
showConfirm(messages).then((res) => {
if (!res) return;
if (payload.key) {
accessStore.update(
@ -1048,6 +1109,51 @@ function _Chat() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
async function uploadImage() {
const images: string[] = [];
images.push(...attachImages);
images.push(
...(await new Promise<string[]>((res, rej) => {
const fileInput = document.createElement("input");
fileInput.type = "file";
fileInput.accept =
"image/png, image/jpeg, image/webp, image/heic, image/heif";
fileInput.multiple = true;
fileInput.onchange = (event: any) => {
setUploading(true);
const files = event.target.files;
const imagesData: string[] = [];
for (let i = 0; i < files.length; i++) {
const file = event.target.files[i];
compressImage(file, 256 * 1024)
.then((dataUrl) => {
imagesData.push(dataUrl);
if (
imagesData.length === 3 ||
imagesData.length === files.length
) {
setUploading(false);
res(imagesData);
}
})
.catch((e) => {
setUploading(false);
rej(e);
});
}
};
fileInput.click();
})),
);
const imagesLength = images.length;
if (imagesLength > 3) {
images.splice(3, imagesLength - 3);
}
setAttachImages(images);
}
return (
<div className={styles.chat} key={session.id}>
<div className="window-header" data-tauri-drag-region>
@ -1109,7 +1215,6 @@ function _Chat() {
</div>
)}
</div>
<PromptToast
showToast={!hitBottom}
showModal={showPromptModal}
@ -1154,15 +1259,29 @@ function _Chat() {
onClick={async () => {
const newMessage = await showPrompt(
Locale.Chat.Actions.Edit,
message.content,
getMessageTextContent(message),
10,
);
let newContent: string | MultimodalContent[] =
newMessage;
const images = getMessageImages(message);
if (images.length > 0) {
newContent = [{ type: "text", text: newMessage }];
for (let i = 0; i < images.length; i++) {
newContent.push({
type: "image_url",
image_url: {
url: images[i],
},
});
}
}
chatStore.updateCurrentSession((session) => {
const m = session.mask.context
.concat(session.messages)
.find((m) => m.id === message.id);
if (m) {
m.content = newMessage;
m.content = newContent;
}
});
}}
@ -1217,7 +1336,11 @@ function _Chat() {
<ChatAction
text={Locale.Chat.Actions.Copy}
icon={<CopyIcon />}
onClick={() => copyToClipboard(message.content)}
onClick={() =>
copyToClipboard(
getMessageTextContent(message),
)
}
/>
</>
)}
@ -1232,7 +1355,7 @@ function _Chat() {
)}
<div className={styles["chat-message-item"]}>
<Markdown
content={message.content}
content={getMessageTextContent(message)}
loading={
(message.preview || message.streaming) &&
message.content.length === 0 &&
@ -1241,12 +1364,42 @@ function _Chat() {
onContextMenu={(e) => onRightClick(e, message)}
onDoubleClickCapture={() => {
if (!isMobileScreen) return;
setUserInput(message.content);
setUserInput(getMessageTextContent(message));
}}
fontSize={fontSize}
parentRef={scrollRef}
defaultShow={i >= messages.length - 6}
/>
{getMessageImages(message).length == 1 && (
<img
className={styles["chat-message-item-image"]}
src={getMessageImages(message)[0]}
alt=""
/>
)}
{getMessageImages(message).length > 1 && (
<div
className={styles["chat-message-item-images"]}
style={
{
"--image-count": getMessageImages(message).length,
} as React.CSSProperties
}
>
{getMessageImages(message).map((image, index) => {
return (
<img
className={
styles["chat-message-item-image-multi"]
}
key={index}
src={image}
alt=""
/>
);
})}
</div>
)}
</div>
<div className={styles["chat-message-action-date"]}>
@ -1266,9 +1419,13 @@ function _Chat() {
<PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
<ChatActions
uploadImage={uploadImage}
setAttachImages={setAttachImages}
setUploading={setUploading}
showPromptModal={() => setShowPromptModal(true)}
scrollToBottom={scrollToBottom}
hitBottom={hitBottom}
uploading={uploading}
showPromptHints={() => {
// Click again to close
if (promptHints.length > 0) {
@ -1281,11 +1438,24 @@ function _Chat() {
onSearch("");
}}
/>
<div className={styles["chat-input-panel-inner"]}>
<label
className={`${styles["chat-input-panel-inner"]} ${
attachImages.length != 0
? styles["chat-input-panel-inner-attach"]
: ""
}`}
htmlFor="chat-input"
>
<textarea
id="chat-input"
ref={inputRef}
className={styles["chat-input"]}
placeholder={Locale.Chat.Input(submitKey)}
placeholder={
accessStore.openaiApiKey
? Locale.Chat.Input(submitKey)
: "请先登录或者在设置页填入你自己的 OpenAI API Key"
}
disabled={!accessStore.openaiApiKey}
onInput={(e) => onInput(e.currentTarget.value)}
value={userInput}
onKeyDown={onInputKeyDown}
@ -1297,14 +1467,37 @@ function _Chat() {
fontSize: config.fontSize,
}}
/>
{attachImages.length != 0 && (
<div className={styles["attach-images"]}>
{attachImages.map((image, index) => {
return (
<div
key={index}
className={styles["attach-image"]}
style={{ backgroundImage: `url("${image}")` }}
>
<div className={styles["attach-image-mask"]}>
<DeleteImageButton
deleteImage={() => {
setAttachImages(
attachImages.filter((_, i) => i !== index),
);
}}
/>
</div>
</div>
);
})}
</div>
)}
<IconButton
icon={<SendWhiteIcon />}
text={Locale.Chat.Send}
text={accessStore.openaiApiKey ? Locale.Chat.Send : "登录"}
className={styles["chat-input-send"]}
type="primary"
onClick={() => doSubmit(userInput)}
/>
</div>
</label>
</div>
{showExport && (

View File

@ -94,6 +94,7 @@
button {
flex-grow: 1;
&:not(:last-child) {
margin-right: 10px;
}
@ -190,6 +191,59 @@
pre {
overflow: hidden;
}
.message-image {
width: 100%;
margin-top: 10px;
}
.message-images {
display: grid;
justify-content: left;
grid-gap: 10px;
grid-template-columns: repeat(var(--image-count), auto);
margin-top: 10px;
}
@media screen and (max-width: 600px) {
$image-width: calc(calc(100vw/2)/var(--image-count));
.message-image-multi {
width: $image-width;
height: $image-width;
}
.message-image {
max-width: calc(100vw/3*2);
}
}
@media screen and (min-width: 600px) {
$max-image-width: calc(900px/3*2/var(--image-count));
$image-width: calc(80vw/3*2/var(--image-count));
.message-image-multi {
width: $image-width;
height: $image-width;
max-width: $max-image-width;
max-height: $max-image-width;
}
.message-image {
max-width: calc(100vw/3*2);
}
}
.message-image-multi {
object-fit: cover;
}
.message-image,
.message-image-multi {
box-sizing: border-box;
border-radius: 10px;
border: rgba($color: #888, $alpha: 0.2) 1px solid;
}
}
&-assistant {
@ -213,6 +267,5 @@
}
}
.default-theme {
}
.default-theme {}
}

View File

@ -12,7 +12,12 @@ import {
showToast,
} from "./ui-lib";
import { IconButton } from "./button";
import { copyToClipboard, downloadAs, useMobileScreen } from "../utils";
import {
copyToClipboard,
downloadAs,
getMessageImages,
useMobileScreen,
} from "../utils";
import CopyIcon from "../icons/copy.svg";
import LoadingIcon from "../icons/three-dots.svg";
@ -34,6 +39,7 @@ import { prettyObject } from "../utils/format";
import { EXPORT_MESSAGE_CLASS_NAME, ModelProvider } from "../constant";
import { getClientConfig } from "../config/client";
import { ClientApi } from "../client/api";
import { getMessageTextContent } from "../utils";
const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
loading: () => <LoadingIcon />,
@ -287,7 +293,7 @@ export function RenderExport(props: {
id={`${m.role}:${i}`}
className={EXPORT_MESSAGE_CLASS_NAME}
>
<Markdown content={m.content} defaultShow />
<Markdown content={getMessageTextContent(m)} defaultShow />
</div>
))}
</div>
@ -307,7 +313,7 @@ export function PreviewActions(props: {
setShouldExport(false);
var api: ClientApi;
if (config.modelConfig.model === "gemini-pro") {
if (config.modelConfig.model.startsWith("gemini")) {
api = new ClientApi(ModelProvider.GeminiPro);
} else {
api = new ClientApi(ModelProvider.GPT);
@ -538,10 +544,8 @@ export function ImagePreviewer(props: {
</div>
<div>
<div className={styles["main-title"]}>NextChat</div>
<div className={styles["sub-title"]}>
github.com/Yidadaa/ChatGPT-Next-Web
</div>
<div className={styles["main-title"]}>GterIng.Com</div>
<div className={styles["sub-title"]}>{session.topic}</div>
<div className={styles["icons"]}>
<ExportAvatar avatar={config.avatar} />
<span className={styles["icon-space"]}>&</span>
@ -555,9 +559,9 @@ export function ImagePreviewer(props: {
<div className={styles["chat-info-item"]}>
{Locale.Exporter.Messages}: {props.messages.length}
</div>
<div className={styles["chat-info-item"]}>
{/* <div className={styles["chat-info-item"]}>
{Locale.Exporter.Topic}: {session.topic}
</div>
</div> */}
<div className={styles["chat-info-item"]}>
{Locale.Exporter.Time}:{" "}
{new Date(
@ -580,10 +584,37 @@ export function ImagePreviewer(props: {
<div className={styles["body"]}>
<Markdown
content={m.content}
content={getMessageTextContent(m)}
fontSize={config.fontSize}
defaultShow
/>
{getMessageImages(m).length == 1 && (
<img
key={i}
src={getMessageImages(m)[0]}
alt="message"
className={styles["message-image"]}
/>
)}
{getMessageImages(m).length > 1 && (
<div
className={styles["message-images"]}
style={
{
"--image-count": getMessageImages(m).length,
} as React.CSSProperties
}
>
{getMessageImages(m).map((src, i) => (
<img
key={i}
src={src}
alt="message"
className={styles["message-image-multi"]}
/>
))}
</div>
)}
</div>
</div>
);
@ -602,8 +633,10 @@ export function MarkdownPreviewer(props: {
props.messages
.map((m) => {
return m.role === "user"
? `## ${Locale.Export.MessageFromYou}:\n${m.content}`
: `## ${Locale.Export.MessageFromChatGPT}:\n${m.content.trim()}`;
? `## ${Locale.Export.MessageFromYou}:\n${getMessageTextContent(m)}`
: `## ${Locale.Export.MessageFromChatGPT}:\n${getMessageTextContent(
m,
).trim()}`;
})
.join("\n\n");

View File

@ -15,6 +15,7 @@
width: var(--window-width);
height: var(--window-height);
transition: all 0.3s cubic-bezier(0.36, 0.66, 0.04, 1);
}
.container {
@ -41,11 +42,11 @@
top: 0;
width: var(--sidebar-width);
box-sizing: border-box;
padding: 20px;
padding: 10px;
background-color: var(--second);
display: flex;
flex-direction: column;
box-shadow: inset -2px 0px 2px 0px rgb(0, 0, 0, 0.05);
box-shadow: inset -1px 0px 1px 0px var(--boxshadow);
position: relative;
transition: width ease 0.05s;
@ -172,7 +173,7 @@
transition: background-color 0.3s ease;
cursor: pointer;
user-select: none;
border: 2px solid transparent;
border: 1.5px solid transparent;
position: relative;
content-visibility: auto;
}
@ -182,7 +183,8 @@
}
.chat-item-selected {
border-color: var(--primary);
// border-color: var(--primary);
border-color: #badde4;
}
.chat-item-title {
@ -231,10 +233,12 @@
}
.narrow-sidebar {
.sidebar-title,
.sidebar-sub-title {
display: none;
}
.sidebar-logo {
position: relative;
display: flex;

View File

@ -171,7 +171,7 @@ export function useLoadData() {
const config = useAppConfig();
var api: ClientApi;
if (config.modelConfig.model === "gemini-pro") {
if (config.modelConfig.model.startsWith("gemini")) {
api = new ClientApi(ModelProvider.GeminiPro);
} else {
api = new ClientApi(ModelProvider.GPT);

View File

@ -22,7 +22,7 @@ import {
useAppConfig,
useChatStore,
} from "../store";
import { ROLES } from "../client/api";
import { MultimodalContent, ROLES } from "../client/api";
import {
Input,
List,
@ -38,7 +38,12 @@ import { useNavigate } from "react-router-dom";
import chatStyle from "./chat.module.scss";
import { useEffect, useState } from "react";
import { copyToClipboard, downloadAs, readFromFile } from "../utils";
import {
copyToClipboard,
downloadAs,
getMessageImages,
readFromFile,
} from "../utils";
import { Updater } from "../typing";
import { ModelConfigList } from "./model-config";
import { FileName, Path } from "../constant";
@ -50,6 +55,7 @@ import {
Draggable,
OnDragEndResponder,
} from "@hello-pangea/dnd";
import { getMessageTextContent } from "../utils";
// drag and drop helper function
function reorder<T>(list: T[], startIndex: number, endIndex: number): T[] {
@ -244,7 +250,7 @@ function ContextPromptItem(props: {
</>
)}
<Input
value={props.prompt.content}
value={getMessageTextContent(props.prompt)}
type="text"
className={chatStyle["context-content"]}
rows={focusingInput ? 5 : 1}
@ -289,7 +295,18 @@ export function ContextPrompts(props: {
};
const updateContextPrompt = (i: number, prompt: ChatMessage) => {
props.updateContext((context) => (context[i] = prompt));
props.updateContext((context) => {
const images = getMessageImages(context[i]);
context[i] = prompt;
if (images.length > 0) {
const text = getMessageTextContent(context[i]);
const newContext: MultimodalContent[] = [{ type: "text", text }];
for (const img of images) {
newContext.push({ type: "image_url", image_url: { url: img } });
}
context[i].content = newContext;
}
});
};
const onDragEnd: OnDragEndResponder = (result) => {

View File

@ -7,6 +7,7 @@ import { MaskAvatar } from "./mask";
import Locale from "../locales";
import styles from "./message-selector.module.scss";
import { getMessageTextContent } from "../utils";
function useShiftRange() {
const [startIndex, setStartIndex] = useState<number>();
@ -103,7 +104,9 @@ export function MessageSelector(props: {
const searchResults = new Set<string>();
if (text.length > 0) {
messages.forEach((m) =>
m.content.includes(text) ? searchResults.add(m.id!) : null,
getMessageTextContent(m).includes(text)
? searchResults.add(m.id!)
: null,
);
}
setSearchIds(searchResults);
@ -219,7 +222,7 @@ export function MessageSelector(props: {
{new Date(m.date).toLocaleString()}
</div>
<div className={`${styles["content"]} one-line`}>
{m.content}
{getMessageTextContent(m)}
</div>
</div>

View File

@ -92,7 +92,7 @@ export function ModelConfigList(props: {
></input>
</ListItem>
{props.modelConfig.model === "gemini-pro" ? null : (
{props.modelConfig.model.startsWith("gemini") ? null : (
<>
<ListItem
title={Locale.Settings.PresencePenalty.Title}

View File

@ -626,7 +626,7 @@ export function Settings() {
const showUsage = accessStore.isAuthorized();
useEffect(() => {
// checks per minutes
checkUpdate();
// checkUpdate();
showUsage && checkUsage();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
@ -700,31 +700,6 @@ export function Settings() {
</Popover>
</ListItem>
<ListItem
title={Locale.Settings.Update.Version(currentVersion ?? "unknown")}
subTitle={
checkingUpdate
? Locale.Settings.Update.IsChecking
: hasNewVersion
? Locale.Settings.Update.FoundUpdate(remoteId ?? "ERROR")
: Locale.Settings.Update.IsLatest
}
>
{checkingUpdate ? (
<LoadingIcon />
) : hasNewVersion ? (
<Link href={updateUrl} target="_blank" className="link">
{Locale.Settings.Update.GoToUpdate}
</Link>
) : (
<IconButton
icon={<ResetIcon></ResetIcon>}
text={Locale.Settings.Update.CheckUpdate}
onClick={() => checkUpdate(true)}
/>
)}
</ListItem>
<ListItem title={Locale.Settings.SendKey}>
<Select
value={config.submitKey}
@ -1081,8 +1056,8 @@ export function Settings() {
></input>
</ListItem>
<ListItem
title={Locale.Settings.Access.Azure.ApiKey.Title}
subTitle={Locale.Settings.Access.Azure.ApiKey.SubTitle}
title={Locale.Settings.Access.Google.ApiKey.Title}
subTitle={Locale.Settings.Access.Google.ApiKey.SubTitle}
>
<PasswordInput
value={accessStore.googleApiKey}
@ -1099,9 +1074,9 @@ export function Settings() {
/>
</ListItem>
<ListItem
title={Locale.Settings.Access.Google.ApiVerion.Title}
title={Locale.Settings.Access.Google.ApiVersion.Title}
subTitle={
Locale.Settings.Access.Google.ApiVerion.SubTitle
Locale.Settings.Access.Google.ApiVersion.SubTitle
}
>
<input

View File

@ -1,4 +1,4 @@
import { useEffect, useRef, useMemo } from "react";
import { useEffect, useRef, useMemo, useState } from "react";
import styles from "./home.module.scss";
@ -15,7 +15,7 @@ import DragIcon from "../icons/drag.svg";
import Locale from "../locales";
import { useAppConfig, useChatStore } from "../store";
import { useAppConfig, useChatStore, useAccessStore } from "../store";
import {
DEFAULT_SIDEBAR_WIDTH,
@ -128,12 +128,38 @@ function useDragSideBar() {
};
}
function EEIcon() {
// 彩蛋
const [count, setCount] = useState(0);
return (
<div className="no-dark" onClick={() => setCount((c) => c + 1)}>
<ChatGptIcon />
{count >= 9 ? (
<video
src="https://registry.npmmirror.com/singlexyz-test/1.0.1/files/test.mp4"
autoPlay
style={{
position: "fixed",
inset: "0",
width: "100%",
height: "100%",
zIndex: 10086,
objectFit: "cover",
}}
/>
) : null}
</div>
);
}
export function SideBar(props: { className?: string }) {
const chatStore = useChatStore();
// drag side bar
const { onDragStart, shouldNarrow } = useDragSideBar();
const navigate = useNavigate();
const accessStore = useAccessStore();
const config = useAppConfig();
const isMobileScreen = useMobileScreen();
const isIOSMobile = useMemo(
@ -155,13 +181,13 @@ export function SideBar(props: { className?: string }) {
>
<div className={styles["sidebar-header"]} data-tauri-drag-region>
<div className={styles["sidebar-title"]} data-tauri-drag-region>
NextChat
GterIng.Com
</div>
<div className={styles["sidebar-sub-title"]}>
{/* <div className={styles["sidebar-sub-title"]}>
Build your own AI assistant.
</div>
</div> */}
<div className={styles["sidebar-logo"] + " no-dark"}>
<ChatGptIcon />
<EEIcon />
</div>
</div>
@ -216,17 +242,25 @@ export function SideBar(props: { className?: string }) {
<IconButton icon={<SettingsIcon />} shadow />
</Link>
</div>
<div className={styles["sidebar-action"]}>
{/* <div className={styles["sidebar-action"]}>
<a href={REPO_URL} target="_blank" rel="noopener noreferrer">
<IconButton icon={<GithubIcon />} shadow />
</a>
</div>
</div> */}
</div>
<div>
<IconButton
icon={<AddIcon />}
text={shouldNarrow ? undefined : Locale.Home.NewChat}
onClick={() => {
if (!accessStore.openaiApiKey) {
return showConfirm("请先登录后操作").then((res) => {
if (res) {
window.location.href =
"https://passport.gter.net/?referer=https://app.gter.net/ai/login?token={token}#/scanLogin)";
}
});
}
if (config.dontShowMaskSplashScreen) {
chatStore.newSession();
navigate(Path.Chat);
@ -238,13 +272,6 @@ export function SideBar(props: { className?: string }) {
/>
</div>
</div>
<div
className={styles["sidebar-drag"]}
onPointerDown={(e) => onDragStart(e as any)}
>
<DragIcon />
</div>
</div>
);
}

View File

@ -8,8 +8,7 @@ export const FETCH_COMMIT_URL = `https://api.github.com/repos/${OWNER}/${REPO}/c
export const FETCH_TAG_URL = `https://api.github.com/repos/${OWNER}/${REPO}/tags?per_page=1`;
export const RUNTIME_CONFIG_DOM = "danger-runtime-config";
export const DEFAULT_CORS_HOST = "https://a.nextweb.fun";
export const DEFAULT_API_HOST = `${DEFAULT_CORS_HOST}/api/proxy`;
export const DEFAULT_API_HOST = "https://api.nextchat.dev";
export const OPENAI_BASE_URL = "https://api.openai.com";
export const GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/";
@ -48,7 +47,7 @@ export enum StoreKey {
Sync = "sync",
}
export const DEFAULT_SIDEBAR_WIDTH = 300;
export const DEFAULT_SIDEBAR_WIDTH = 260;
export const MAX_SIDEBAR_WIDTH = 500;
export const MIN_SIDEBAR_WIDTH = 230;
export const NARROW_SIDEBAR_WIDTH = 100;
@ -89,6 +88,7 @@ export const Azure = {
export const Google = {
ExampleEndpoint: "https://generativelanguage.googleapis.com/",
ChatPath: "v1beta/models/gemini-pro:generateContent",
VisionChatPath: "v1beta/models/gemini-pro-vision:generateContent",
// /api/openai/v1/chat/completions
};
@ -104,6 +104,7 @@ Latex block: $$e=mc^2$$
`;
export const SUMMARIZE_MODEL = "gpt-3.5-turbo";
export const GEMINI_SUMMARIZE_MODEL = "gemini-pro";
export const KnowledgeCutOffDate: Record<string, string> = {
default: "2021-09",
@ -126,6 +127,15 @@ export const DEFAULT_MODELS = [
providerType: "openai",
},
},
{
name: "gpt-4-turbo",
available: true,
provider: {
id: "openai",
providerName: "OpenAI",
providerType: "openai",
},
},
{
name: "gpt-4-0314",
available: true,
@ -144,15 +154,15 @@ export const DEFAULT_MODELS = [
providerType: "openai",
},
},
{
name: "gpt-4-32k",
available: true,
provider: {
id: "openai",
providerName: "OpenAI",
providerType: "openai",
},
},
// {
// name: "gpt-4-32k",
// available: true,
// provider: {
// id: "openai",
// providerName: "OpenAI",
// providerType: "openai",
// },
// },
{
name: "gpt-4-32k-0314",
available: true,
@ -162,42 +172,6 @@ export const DEFAULT_MODELS = [
providerType: "openai",
},
},
{
name: "gpt-4-32k-0613",
available: true,
provider: {
id: "openai",
providerName: "OpenAI",
providerType: "openai",
},
},
{
name: "gpt-4-turbo-preview",
available: true,
provider: {
id: "openai",
providerName: "OpenAI",
providerType: "openai",
},
},
{
name: "gpt-4-1106-preview",
available: true,
provider: {
id: "openai",
providerName: "OpenAI",
providerType: "openai",
},
},
{
name: "gpt-4-0125-preview",
available: true,
provider: {
id: "openai",
providerName: "OpenAI",
providerType: "openai",
},
},
{
name: "gpt-4-vision-preview",
available: true,
@ -216,15 +190,15 @@ export const DEFAULT_MODELS = [
providerType: "openai",
},
},
{
name: "gpt-3.5-turbo-0125",
available: true,
provider: {
id: "openai",
providerName: "OpenAI",
providerType: "openai",
},
},
// {
// name: "gpt-3.5-turbo-0125",
// available: true,
// provider: {
// id: "openai",
// providerName: "OpenAI",
// providerType: "openai",
// },
// },
{
name: "gpt-3.5-turbo-0301",
available: true,
@ -279,6 +253,87 @@ export const DEFAULT_MODELS = [
providerType: "google",
},
},
{
name: "gemini-pro-vision",
available: true,
provider: {
id: "google",
providerName: "Google",
providerType: "google",
},
},
{
name: "claude-3-opus-20240229",
available: true,
provider: {
id: "claude",
providerName: "Claude",
providerType: "Claude",
},
},
{
name: "claude-3-sonnet-20240229",
available: true,
provider: {
id: "claude",
providerName: "Claude",
providerType: "Claude",
},
},
{
name: "claude-3-haiku-20240307",
available: true,
provider: {
id: "claude",
providerName: "Claude",
providerType: "Claude",
},
},
{
name: "moonshot-v1-8k",
available: true,
provider: {
id: "moonshot",
providerName: "Moonshot AI",
providerType: "moonshot",
},
},
{
name: "moonshot-v1-32k",
available: true,
provider: {
id: "moonshot",
providerName: "Moonshot AI",
providerType: "moonshot",
},
},
{
name: "moonshot-v1-128k",
available: true,
provider: {
id: "moonshot",
providerName: "Moonshot AI",
providerType: "moonshot",
},
},
{
name: "deepseek-coder",
available: true,
provider: {
id: "deepseek",
providerName: "deepseek AI",
providerType: "deepseek",
},
},
{
name: "deepseek-chat",
available: true,
provider: {
id: "deepseek",
providerName: "deepseek AI",
providerType: "deepseek",
},
},
] as const;
export const CHAT_PAGE_SIZE = 15;

1
app/icons/image.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" height="16" width="16" version="1.1" xml:space="preserve" style=""><rect id="backgroundrect" width="100%" height="100%" x="0" y="0" fill="none" stroke="none"/><g class="currentLayer" style=""><title>Layer 1</title><g id="svg_1" class="" fill="#333" fill-opacity="1"><polygon points="2.4690866470336914,2.4690725803375244 4.447190761566162,2.4690725803375244 4.447190761566162,1.6882386207580566 1.6882381439208984,1.6882386207580566 1.6882381439208984,4.44719123840332 2.4690866470336914,4.44719123840332 " id="svg_2" fill="#333" fill-opacity="1"/><polygon points="11.552804470062256,1.6882386207580566 11.552804470062256,2.4690725803375244 13.530910968780518,2.4690725803375244 13.530910968780518,4.44719123840332 14.311760425567627,4.44719123840332 14.311760425567627,1.6882386207580566 " id="svg_3" fill="#333" fill-opacity="1"/><polygon points="13.530910968780518,13.530919075012207 11.552804470062256,13.530919075012207 11.552804470062256,14.311760902404785 14.311760425567627,14.311760902404785 14.311760425567627,11.552801132202148 13.530910968780518,11.552801132202148 " id="svg_4" fill="#333" fill-opacity="1"/><polygon points="2.4690866470336914,11.552801132202148 1.6882381439208984,11.552801132202148 1.6882381439208984,14.311760902404785 4.447190761566162,14.311760902404785 4.447190761566162,13.530919075012207 2.4690866470336914,13.530919075012207 " id="svg_5" fill="#333" fill-opacity="1"/><path d="M8.830417847409231,6.243117030680995 c0.68169614081525,0 1.2363241834494423,-0.5546280426341942 1.2363241834494423,-1.2363241834494423 S9.51214001610201,3.770468663782117 8.830417847409231,3.770468663782117 s-1.2363241834494423,0.5546280426341942 -1.2363241834494423,1.2363241834494423 S8.14872170659398,6.243117030680995 8.830417847409231,6.243117030680995 z" id="svg_6" fill="#333" fill-opacity="1"/><polygon points="3.7704806327819824,12.229532241821289 12.229516506195068,12.229532241821289 12.229516506195068,9.709510803222656 10.70320463180542,8.099010467529297 8.852166652679443,9.175727844238281 6.275332450866699,7.334256172180176 3.7704806327819824,9.977211952209473 " id="svg_7" fill="#333" fill-opacity="1"/></g></g></svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

1
app/icons/loading.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#fff" style=""><rect id="backgroundrect" width="100%" height="100%" x="0" y="0" fill="none" stroke="none" style="" class="" /><g class="currentLayer" style=""><title>Layer 1</title><circle cx="4" cy="8" r="1.926" fill="#333" id="svg_1" class=""><animate attributeName="r" begin="0s" calcMode="linear" dur="0.8s" from="2" repeatCount="indefinite" to="2" values="2;1.2;2" /><animate attributeName="fill-opacity" begin="0s" calcMode="linear" dur="0.8s" from="1" repeatCount="indefinite" to="1" values="1;.5;1" /></circle><circle cx="8" cy="8" r="1.2736" fill="#333" fill-opacity=".3" id="svg_2" class=""><animate attributeName="r" begin="0s" calcMode="linear" dur="0.8s" from="1.2" repeatCount="indefinite" to="1.2" values="1.2;2;1.2" /><animate attributeName="fill-opacity" begin="0s" calcMode="linear" dur="0.8s" from=".5" repeatCount="indefinite" to=".5" values=".5;1;.5" /></circle><circle cx="12" cy="8" r="1.926" fill="#333" id="svg_3" class=""><animate attributeName="r" begin="0s" calcMode="linear" dur="0.8s" from="2" repeatCount="indefinite" to="2" values="2;1.2;2" /><animate attributeName="fill-opacity" begin="0s" calcMode="linear" dur="0.8s" from="1" repeatCount="indefinite" to="1" values="1;.5;1" /></circle></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -10,7 +10,7 @@ import { GoogleTagManager } from "@next/third-parties/google";
const serverConfig = getServerSideConfig();
export const metadata: Metadata = {
title: "NextChat",
title: "GterIngChat",
description: "Your personal ChatGPT Chat Bot.",
viewport: {
width: "device-width",
@ -22,7 +22,7 @@ export const metadata: Metadata = {
{ media: "(prefers-color-scheme: dark)", color: "#151515" },
],
appleWebApp: {
title: "NextChat",
title: "GterIngChat",
statusBarStyle: "default",
},
};

View File

@ -8,7 +8,7 @@ const cn = {
Error: {
Unauthorized: isApp
? "检测到无效 API Key请前往[设置](/#/settings)页检查 API Key 是否配置正确。"
: "访问密码不正确或为空,请前往[登录](/#/auth)页输入正确的访问密码,或者在[设置](/#/settings)页填入你自己的 OpenAI API Key。",
: "访问密码不正确或为空,请前往[登录](https://passport.gter.net/?referer=https://app.gter.net/ai/login?token={token}#/scanLogin)页输入正确的访问密码,或者在[设置](/#/settings)页填入你自己的 OpenAI API Key。",
},
Auth: {
Title: "需要密码",
@ -63,6 +63,7 @@ const cn = {
Masks: "所有面具",
Clear: "清除聊天",
Settings: "对话设置",
UploadImage: "上传图片",
},
Rename: "重命名对话",
Typing: "正在输入…",
@ -314,19 +315,19 @@ const cn = {
},
Google: {
ApiKey: {
Title: "接口密钥",
SubTitle: "使用自定义 Google AI Studio API Key 绕过密码访问限制",
Placeholder: "Google AI Studio API Key",
Title: "API 密钥",
SubTitle: "从 Google AI 获取您的 API 密钥",
Placeholder: "输入您的 Google AI Studio API 密钥",
},
Endpoint: {
Title: "接口地址",
SubTitle: "不包含请求路径,样例:",
Title: "终端地址",
SubTitle: "例:",
},
ApiVerion: {
Title: "接口版本 (gemini-pro api version)",
SubTitle: "选择指定的部分版本",
ApiVersion: {
Title: "API 版本(仅适用于 gemini-pro",
SubTitle: "选择一个特定的 API 版本",
},
},
CustomModel: {

View File

@ -65,6 +65,7 @@ const en: LocaleType = {
Masks: "Masks",
Clear: "Clear Context",
Settings: "Settings",
UploadImage: "Upload Images",
},
Rename: "Rename Chat",
Typing: "Typing…",
@ -322,9 +323,8 @@ const en: LocaleType = {
Google: {
ApiKey: {
Title: "API Key",
SubTitle:
"Bypass password access restrictions using a custom Google AI Studio API Key",
Placeholder: "Google AI Studio API Key",
SubTitle: "Obtain your API Key from Google AI",
Placeholder: "Enter your Google AI Studio API Key",
},
Endpoint: {
@ -332,9 +332,9 @@ const en: LocaleType = {
SubTitle: "Example:",
},
ApiVerion: {
Title: "API Version (gemini-pro api version)",
SubTitle: "Select a specific part version",
ApiVersion: {
Title: "API Version (specific to gemini-pro)",
SubTitle: "Select a specific API version",
},
},
},

View File

@ -334,7 +334,7 @@ const sk: PartialLocaleType = {
SubTitle: "Príklad:",
},
ApiVerion: {
ApiVersion: {
Title: "Verzia API (gemini-pro verzia API)",
SubTitle: "Vyberte špecifickú verziu časti",
},

View File

@ -12,7 +12,9 @@ import { ensure } from "../utils/clone";
let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
const DEFAULT_OPENAI_URL =
getClientConfig()?.buildMode === "export" ? DEFAULT_API_HOST : ApiPath.OpenAI;
getClientConfig()?.buildMode === "export"
? DEFAULT_API_HOST + "/api/proxy/openai"
: ApiPath.OpenAI;
const DEFAULT_ACCESS_STATE = {
accessCode: "",
@ -80,7 +82,7 @@ export const useAccessStore = createPersistStore(
fetch() {
if (fetchState > 0 || getClientConfig()?.buildMode === "export") return;
fetchState = 1;
fetch("/api/config", {
fetch("https://app.gter.net/ai/config", {
method: "post",
body: null,
headers: {
@ -88,9 +90,10 @@ export const useAccessStore = createPersistStore(
},
})
.then((res) => res.json())
.then((res: DangerConfig) => {
console.log("[Config] got config from server", res);
set(() => ({ ...res }));
.then((res) => {
var config = res.data;
console.log("[Config] got config from server", config);
set(() => ({ ...config }));
})
.catch(() => {
console.error("[Config] failed to fetch config");

View File

@ -1,4 +1,4 @@
import { trimTopic } from "../utils";
import { trimTopic, getMessageTextContent } from "../utils";
import Locale, { getLang } from "../locales";
import { showToast } from "../components/ui-lib";
@ -12,8 +12,9 @@ import {
ModelProvider,
StoreKey,
SUMMARIZE_MODEL,
GEMINI_SUMMARIZE_MODEL,
} from "../constant";
import { ClientApi, RequestMessage } from "../client/api";
import { ClientApi, RequestMessage, MultimodalContent } from "../client/api";
import { ChatControllerPool } from "../client/controller";
import { prettyObject } from "../utils/format";
import { estimateTokenLength } from "../utils/token";
@ -84,22 +85,35 @@ function createEmptySession(): ChatSession {
function getSummarizeModel(currentModel: string) {
// if it is using gpt-* models, force to use 3.5 to summarize
return currentModel.startsWith("gpt") ? SUMMARIZE_MODEL : currentModel;
if (currentModel.startsWith("gpt")) {
return SUMMARIZE_MODEL;
}
if (currentModel.startsWith("gemini-pro")) {
return GEMINI_SUMMARIZE_MODEL;
}
return currentModel;
}
function countMessages(msgs: ChatMessage[]) {
return msgs.reduce((pre, cur) => pre + estimateTokenLength(cur.content), 0);
return msgs.reduce(
(pre, cur) => pre + estimateTokenLength(getMessageTextContent(cur)),
0,
);
}
function fillTemplateWith(input: string, modelConfig: ModelConfig) {
const cutoff = KnowledgeCutOffDate[modelConfig.model] ?? KnowledgeCutOffDate.default;
const cutoff =
KnowledgeCutOffDate[modelConfig.model] ?? KnowledgeCutOffDate.default;
// Find the model in the DEFAULT_MODELS array that matches the modelConfig.model
const modelInfo = DEFAULT_MODELS.find(m => m.name === modelConfig.model);
if (!modelInfo) {
throw new Error(`Model ${modelConfig.model} not found in DEFAULT_MODELS array.`);
}
const modelInfo = DEFAULT_MODELS.find((m) => m.name === modelConfig.model);
var serviceProvider = "OpenAI";
if (modelInfo) {
// TODO: auto detect the providerName from the modelConfig.model
// Directly use the providerName from the modelInfo
const serviceProvider = modelInfo.provider.providerName;
serviceProvider = modelInfo.provider.providerName;
}
const vars = {
ServiceProvider: serviceProvider,
@ -119,7 +133,7 @@ function fillTemplateWith(input: string, modelConfig: ModelConfig) {
}
Object.entries(vars).forEach(([name, value]) => {
const regex = new RegExp(`{{${name}}}`, 'g');
const regex = new RegExp(`{{${name}}}`, "g");
output = output.replace(regex, value.toString()); // Ensure value is a string
});
@ -276,16 +290,36 @@ export const useChatStore = createPersistStore(
get().summarizeSession();
},
async onUserInput(content: string) {
async onUserInput(content: string, attachImages?: string[]) {
const session = get().currentSession();
const modelConfig = session.mask.modelConfig;
const userContent = fillTemplateWith(content, modelConfig);
console.log("[User Input] after template: ", userContent);
const userMessage: ChatMessage = createMessage({
let mContent: string | MultimodalContent[] = userContent;
if (attachImages && attachImages.length > 0) {
mContent = [
{
type: "text",
text: userContent,
},
];
mContent = mContent.concat(
attachImages.map((url) => {
return {
type: "image_url",
image_url: {
url: url,
},
};
}),
);
}
let userMessage: ChatMessage = createMessage({
role: "user",
content: userContent,
content: mContent,
});
const botMessage: ChatMessage = createMessage({
@ -303,7 +337,7 @@ export const useChatStore = createPersistStore(
get().updateCurrentSession((session) => {
const savedUserMessage = {
...userMessage,
content,
content: mContent,
};
session.messages = session.messages.concat([
savedUserMessage,
@ -312,7 +346,7 @@ export const useChatStore = createPersistStore(
});
var api: ClientApi;
if (modelConfig.model === "gemini-pro") {
if (modelConfig.model.startsWith("gemini")) {
api = new ClientApi(ModelProvider.GeminiPro);
} else {
api = new ClientApi(ModelProvider.GPT);
@ -457,7 +491,7 @@ export const useChatStore = createPersistStore(
) {
const msg = messages[i];
if (!msg || msg.isError) continue;
tokenCount += estimateTokenLength(msg.content);
tokenCount += estimateTokenLength(getMessageTextContent(msg));
reversedRecentMessages.push(msg);
}
@ -497,7 +531,7 @@ export const useChatStore = createPersistStore(
const modelConfig = session.mask.modelConfig;
var api: ClientApi;
if (modelConfig.model === "gemini-pro") {
if (modelConfig.model.startsWith("gemini")) {
api = new ClientApi(ModelProvider.GeminiPro);
} else {
api = new ClientApi(ModelProvider.GPT);

View File

@ -31,8 +31,8 @@ export const DEFAULT_CONFIG = {
submitKey: SubmitKey.Enter,
avatar: "1f603",
fontSize: 14,
theme: Theme.Auto as Theme,
tightBorder: !!getClientConfig()?.isApp,
theme: Theme.Light as Theme,
tightBorder: true,
sendPreviewBubble: true,
enableAutoGenerateTitle: true,
sidebarWidth: DEFAULT_SIDEBAR_WIDTH,
@ -91,7 +91,7 @@ export const ModalConfigValidator = {
return limitNumber(x, -2, 2, 0);
},
temperature(x: number) {
return limitNumber(x, 0, 1, 1);
return limitNumber(x, 0, 2, 1);
},
top_p(x: number) {
return limitNumber(x, 0, 1, 1);

View File

@ -9,7 +9,7 @@
--black: rgb(48, 48, 48);
--gray: rgb(250, 250, 250);
--primary: rgb(29, 147, 171);
--second: rgb(231, 248, 255);
--second: rgb(233 243 247);
--hover-color: #f3f3f3;
--bar-color: rgba(0, 0, 0, 0.1);
--theme-color: var(--gray);
@ -20,6 +20,8 @@
/* stroke */
--border-in-light: 1px solid rgb(222, 222, 222);
--boxshadow: rgb(0, 0, 0, 0.05);
}
@mixin dark {
@ -30,9 +32,11 @@
--black: rgb(187, 187, 187);
--gray: rgb(21, 21, 21);
--primary: rgb(29, 147, 171);
--second: rgb(27 38 42);
--second: rgb(30 30 30 / 0%);
--hover-color: #323232;
--boxshadow: rgba(255, 255, 255, 0.1);
--bar-color: rgba(255, 255, 255, 0.1);
--border-in-light: 1px solid rgba(255, 255, 255, 0.192);
@ -61,7 +65,7 @@
--window-width: 90vw;
--window-height: 90vh;
--sidebar-width: 300px;
--sidebar-width: 200px;
--window-content-width: calc(100% - var(--sidebar-width));
--message-max-width: 80%;
--full-height: 100%;

View File

@ -1,5 +1,5 @@
.window-header {
padding: 14px 20px;
padding: 8px 20px;
border-bottom: rgba(0, 0, 0, 0.1) 1px solid;
position: relative;
@ -13,7 +13,7 @@
overflow: hidden;
.window-header-main-title {
font-size: 20px;
font-size: 18px;
font-weight: bolder;
overflow: hidden;
text-overflow: ellipsis;
@ -23,14 +23,24 @@
}
.window-header-sub-title {
font-size: 14px;
font-size: 13px;
}
}
.window-actions {
display: inline-flex;
}
.window-action-button {
button {
padding: 8px;
}
}
.window-action-button:not(:first-child) {
margin-left: 10px;
}

View File

@ -1,12 +1,16 @@
import { useEffect, useState } from "react";
import { showToast } from "./components/ui-lib";
import Locale from "./locales";
import { RequestMessage } from "./client/api";
import { DEFAULT_MODELS } from "./constant";
export function trimTopic(topic: string) {
// Fix an issue where double quotes still show in the Indonesian language
// This will remove the specified punctuation from the end of the string
// and also trim quotes from both the start and end if they exist.
return topic.replace(/^["“”]+|["“”]+$/g, "").replace(/[,。!?”“"、,.!?]*$/, "");
return topic
.replace(/^["“”]+|["“”]+$/g, "")
.replace(/[,。!?”“"、,.!?]*$/, "");
}
export async function copyToClipboard(text: string) {
@ -40,8 +44,8 @@ export async function downloadAs(text: string, filename: string) {
defaultPath: `${filename}`,
filters: [
{
name: `${filename.split('.').pop()} files`,
extensions: [`${filename.split('.').pop()}`],
name: `${filename.split(".").pop()} files`,
extensions: [`${filename.split(".").pop()}`],
},
{
name: "All Files",
@ -54,7 +58,7 @@ export async function downloadAs(text: string, filename: string) {
try {
await window.__TAURI__.fs.writeBinaryFile(
result,
new Uint8Array([...text].map((c) => c.charCodeAt(0)))
new Uint8Array([...text].map((c) => c.charCodeAt(0))),
);
showToast(Locale.Download.Success);
} catch (error) {
@ -79,6 +83,49 @@ export async function downloadAs(text: string, filename: string) {
document.body.removeChild(element);
}
}
export function compressImage(file: File, maxSize: number): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (readerEvent: any) => {
const image = new Image();
image.onload = () => {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let width = image.width;
let height = image.height;
let quality = 0.9;
let dataUrl;
do {
canvas.width = width;
canvas.height = height;
ctx?.clearRect(0, 0, canvas.width, canvas.height);
ctx?.drawImage(image, 0, 0, width, height);
dataUrl = canvas.toDataURL("image/jpeg", quality);
if (dataUrl.length < maxSize) break;
if (quality > 0.5) {
// Prioritize quality reduction
quality -= 0.1;
} else {
// Then reduce the size
width *= 0.9;
height *= 0.9;
}
} while (dataUrl.length > maxSize);
resolve(dataUrl);
};
image.onerror = reject;
image.src = readerEvent.target.result;
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
export function readFromFile() {
return new Promise<string>((res, rej) => {
const fileInput = document.createElement("input");
@ -212,8 +259,43 @@ export function getCSSVar(varName: string) {
export function isMacOS(): boolean {
if (typeof window !== "undefined") {
let userAgent = window.navigator.userAgent.toLocaleLowerCase();
const macintosh = /iphone|ipad|ipod|macintosh/.test(userAgent)
return !!macintosh
const macintosh = /iphone|ipad|ipod|macintosh/.test(userAgent);
return !!macintosh;
}
return false
return false;
}
export function getMessageTextContent(message: RequestMessage) {
if (typeof message.content === "string") {
return message.content;
}
for (const c of message.content) {
if (c.type === "text") {
return c.text ?? "";
}
}
return "";
}
export function getMessageImages(message: RequestMessage): string[] {
if (typeof message.content === "string") {
return [];
}
const urls: string[] = [];
for (const c of message.content) {
if (c.type === "image_url") {
urls.push(c.image_url?.url ?? "");
}
}
return urls;
}
export function isVisionModel(model: string) {
return (
model.startsWith("claude-3-sonnet-20240229") ||
model.startsWith("claude-3-haiku-20240307") ||
model.startsWith("gpt-4-vision") ||
model.startsWith("gemini-pro-vision") ||
!DEFAULT_MODELS.find((m) => m.name == model)
);
}

View File

@ -1,8 +1,8 @@
import { getClientConfig } from "../config/client";
import { ApiPath, DEFAULT_CORS_HOST } from "../constant";
import { ApiPath, DEFAULT_API_HOST } from "../constant";
export function corsPath(path: string) {
const baseUrl = getClientConfig()?.isApp ? `${DEFAULT_CORS_HOST}` : "";
const baseUrl = getClientConfig()?.isApp ? `${DEFAULT_API_HOST}` : "";
if (!path.startsWith("/")) {
path = "/" + path;

View File

@ -1,38 +0,0 @@
version: "3.9"
services:
chatgpt-next-web:
profiles: [ "no-proxy" ]
container_name: chatgpt-next-web
image: yidadaa/chatgpt-next-web
ports:
- 3000:3000
environment:
- OPENAI_API_KEY=$OPENAI_API_KEY
- GOOGLE_API_KEY=$GOOGLE_API_KEY
- CODE=$CODE
- BASE_URL=$BASE_URL
- OPENAI_ORG_ID=$OPENAI_ORG_ID
- HIDE_USER_API_KEY=$HIDE_USER_API_KEY
- DISABLE_GPT4=$DISABLE_GPT4
- ENABLE_BALANCE_QUERY=$ENABLE_BALANCE_QUERY
- DISABLE_FAST_LINK=$DISABLE_FAST_LINK
- OPENAI_SB=$OPENAI_SB
chatgpt-next-web-proxy:
profiles: [ "proxy" ]
container_name: chatgpt-next-web-proxy
image: yidadaa/chatgpt-next-web
ports:
- 3000:3000
environment:
- OPENAI_API_KEY=$OPENAI_API_KEY
- GOOGLE_API_KEY=$GOOGLE_API_KEY
- CODE=$CODE
- PROXY_URL=$PROXY_URL
- BASE_URL=$BASE_URL
- OPENAI_ORG_ID=$OPENAI_ORG_ID
- HIDE_USER_API_KEY=$HIDE_USER_API_KEY
- DISABLE_GPT4=$DISABLE_GPT4
- ENABLE_BALANCE_QUERY=$ENABLE_BALANCE_QUERY
- DISABLE_FAST_LINK=$DISABLE_FAST_LINK
- OPENAI_SB=$OPENAI_SB

View File

@ -1,42 +0,0 @@
# Cloudflare Pages 部署指南
## 如何新建项目
在 Github 上 fork 本项目,然后登录到 dash.cloudflare.com 并进入 Pages。
1. 点击 "Create a project"。
2. 选择 "Connect to Git"。
3. 关联 Cloudflare Pages 和你的 GitHub 账号。
4. 选中你 fork 的此项目。
5. 点击 "Begin setup"。
6. 对于 "Project name" 和 "Production branch",可以使用默认值,也可以根据需要进行更改。
7. 在 "Build Settings" 中,选择 "Framework presets" 选项并选择 "Next.js"。
8. 由于 node:buffer 的 bug暂时不要使用默认的 "Build command"。请使用以下命令:
```
npx @cloudflare/next-on-pages@1.5.0
```
9. 对于 "Build output directory",使用默认值并且不要修改。
10. 不要修改 "Root Directory"。
11. 对于 "Environment variables",点击 ">" 然后点击 "Add variable"。按照以下信息填写:
- `NODE_VERSION=20.1`
- `NEXT_TELEMETRY_DISABLE=1`
- `OPENAI_API_KEY=你自己的API Key`
- `YARN_VERSION=1.22.19`
- `PHP_VERSION=7.4`
根据实际需要,可以选择填写以下选项:
- `CODE= 可选填,访问密码,可以使用逗号隔开多个密码`
- `OPENAI_ORG_ID= 可选填,指定 OpenAI 中的组织 ID`
- `HIDE_USER_API_KEY=1 可选,不让用户自行填入 API Key`
- `DISABLE_GPT4=1 可选,不让用户使用 GPT-4`
- `ENABLE_BALANCE_QUERY=1 可选,启用余额查询功能`
- `DISABLE_FAST_LINK=1 可选,禁用从链接解析预制设置`
12. 点击 "Save and Deploy"。
13. 点击 "Cancel deployment",因为需要填写 Compatibility flags。
14. 前往 "Build settings"、"Functions",找到 "Compatibility flags"。
15. 在 "Configure Production compatibility flag" 和 "Configure Preview compatibility flag" 中填写 "nodejs_compat"。
16. 前往 "Deployments",点击 "Retry deployment"。
17. Enjoy.

View File

@ -1,43 +0,0 @@
# Cloudflare Pages Deployment Guide
## How to create a new project
Fork this project on GitHub, then log in to dash.cloudflare.com and go to Pages.
1. Click "Create a project".
2. Choose "Connect to Git".
3. Connect Cloudflare Pages to your GitHub account.
4. Select the forked project.
5. Click "Begin setup".
6. For "Project name" and "Production branch", use the default values or change them as needed.
7. In "Build Settings", choose the "Framework presets" option and select "Next.js".
8. Do not use the default "Build command" due to a node:buffer bug. Instead, use the following command:
```
npx @cloudflare/next-on-pages --experimental-minify
```
9. For "Build output directory", use the default value and do not modify it.
10. Do not modify "Root Directory".
11. For "Environment variables", click ">" and then "Add variable". Fill in the following information:
- `NODE_VERSION=20.1`
- `NEXT_TELEMETRY_DISABLE=1`
- `OPENAI_API_KEY=your_own_API_key`
- `YARN_VERSION=1.22.19`
- `PHP_VERSION=7.4`
Optionally fill in the following based on your needs:
- `CODE= Optional, access passwords, multiple passwords can be separated by commas`
- `OPENAI_ORG_ID= Optional, specify the organization ID in OpenAI`
- `HIDE_USER_API_KEY=1 Optional, do not allow users to enter their own API key`
- `DISABLE_GPT4=1 Optional, do not allow users to use GPT-4`
- `ENABLE_BALANCE_QUERY=1 Optional, allow users to query balance`
- `DISABLE_FAST_LINK=1 Optional, disable parse settings from url`
- `OPENAI_SB=1 Optionaluse the third-party OpenAI-SB API`
12. Click "Save and Deploy".
13. Click "Cancel deployment" because you need to fill in Compatibility flags.
14. Go to "Build settings", "Functions", and find "Compatibility flags".
15. Fill in "nodejs_compat" for both "Configure Production compatibility flag" and "Configure Preview compatibility flag".
16. Go to "Deployments" and click "Retry deployment".
17. Enjoy.

View File

@ -1,37 +0,0 @@
# Guía de implementación de Cloudflare Pages
## Cómo crear un nuevo proyecto
Bifurca el proyecto en Github, luego inicia sesión en dash.cloudflare.com y ve a Pages.
1. Haga clic en "Crear un proyecto".
2. Selecciona Conectar a Git.
3. Vincula páginas de Cloudflare a tu cuenta de GitHub.
4. Seleccione este proyecto que bifurcó.
5. Haga clic en "Comenzar configuración".
6. Para "Nombre del proyecto" y "Rama de producción", puede utilizar los valores predeterminados o cambiarlos según sea necesario.
7. En Configuración de compilación, seleccione la opción Ajustes preestablecidos de Framework y seleccione Siguiente.js.
8. Debido a los errores de node:buffer, no use el "comando Construir" predeterminado por ahora. Utilice el siguiente comando:
npx https://prerelease-registry.devprod.cloudflare.dev/next-on-pages/runs/4930842298/npm-package-next-on-pages-230 --experimental-minify
9. Para "Generar directorio de salida", utilice los valores predeterminados y no los modifique.
10. No modifique el "Directorio raíz".
11. Para "Variables de entorno", haga clic en ">" y luego haga clic en "Agregar variable". Rellene la siguiente información:
* `NODE_VERSION=20.1`
* `NEXT_TELEMETRY_DISABLE=1`
* `OPENAI_API_KEY=你自己的API Key`
* `YARN_VERSION=1.22.19`
* `PHP_VERSION=7.4`
Dependiendo de sus necesidades reales, puede completar opcionalmente las siguientes opciones:
* `CODE= 可选填,访问密码,可以使用逗号隔开多个密码`
* `OPENAI_ORG_ID= 可选填,指定 OpenAI 中的组织 ID`
* `HIDE_USER_API_KEY=1 可选,不让用户自行填入 API Key`
* `DISABLE_GPT4=1 可选,不让用户使用 GPT-4`
12. Haga clic en "Guardar e implementar".
13. Haga clic en "Cancelar implementación" porque necesita rellenar los indicadores de compatibilidad.
14. Vaya a "Configuración de compilación", "Funciones" y busque "Indicadores de compatibilidad".
15. Rellene "nodejs_compat" en "Configurar indicador de compatibilidad de producción" y "Configurar indicador de compatibilidad de vista previa".
16. Vaya a "Implementaciones" y haga clic en "Reintentar implementación".
17. Disfrutar.

View File

@ -1,38 +0,0 @@
# Cloudflare Pages 導入ガイド
## 新規プロジェクトの作成方法
GitHub でこのプロジェクトをフォークし、dash.cloudflare.com にログインして Pages にアクセスします。
1. "Create a project" をクリックする。
2. "Connect to Git" を選択する。
3. Cloudflare Pages を GitHub アカウントに接続します。
4. フォークしたプロジェクトを選択します。
5. "Begin setup" をクリックする。
6. "Project name" と "Production branch" はデフォルト値を使用するか、必要に応じて変更してください。
7. "Build Settings" で、"Framework presets" オプションを選択し、"Next.js" を選択します。
8. node:buffer のバグのため、デフォルトの "Build command" は使用しないでください。代わりに、以下のコマンドを使用してください:
```
npx https://prerelease-registry.devprod.cloudflare.dev/next-on-pages/runs/4930842298/npm-package-next-on-pages-230 --experimental-minify
```
9. "Build output directory" はデフォルト値を使用し、変更しない。
10. "Root Directory" を変更しない。
11. "Environment variables" は、">" をクリックし、"Add variable" をクリックします。そして以下の情報を入力します:
- `NODE_VERSION=20.1`
- `NEXT_TELEMETRY_DISABLE=1`
- `OPENAI_API_KEY=your_own_API_key`
- `YARN_VERSION=1.22.19`
- `PHP_VERSION=7.4`
必要に応じて、以下の項目を入力してください:
- `CODE= Optional, access passwords, multiple passwords can be separated by commas`
- `OPENAI_ORG_ID= Optional, specify the organization ID in OpenAI`
- `HIDE_USER_API_KEY=1 Optional, do not allow users to enter their own API key`
- `DISABLE_GPT4=1 Optional, do not allow users to use GPT-4`
12. "Save and Deploy" をクリックする。
13. 互換性フラグを記入する必要があるため、"Cancel deployment" をクリックする。
14. "Build settings" の "Functions" から "Compatibility flags" を見つける。
15. "Configure Production compatibility flag" と "Configure Preview compatibility flag" の両方に "nodejs_compat "を記入する。
16. "Deployments" に移動し、"Retry deployment" をクリックします。
17. お楽しみください。

View File

@ -1,39 +0,0 @@
## Cloudflare 페이지 배포 가이드
## 새 프로젝트를 만드는 방법
이 프로젝트를 Github에서 포크한 다음 dash.cloudflare.com에 로그인하고 페이지로 이동합니다.
1. "프로젝트 만들기"를 클릭합니다.
2. "Git에 연결"을 선택합니다.
3. Cloudflare 페이지를 GitHub 계정과 연결합니다.
4. 포크한 프로젝트를 선택합니다.
5. "설정 시작"을 클릭합니다.
6. "프로젝트 이름" 및 "프로덕션 브랜치"의 기본값을 사용하거나 필요에 따라 변경합니다.
7. "빌드 설정"에서 "프레임워크 프리셋" 옵션을 선택하고 "Next.js"를 선택합니다.
8. node:buffer 버그로 인해 지금은 기본 "빌드 명령어"를 사용하지 마세요. 다음 명령을 사용하세요:
``
npx https://prerelease-registry.devprod.cloudflare.dev/next-on-pages/runs/4930842298/npm-package-next-on-pages-230 --experimental- minify
```
9. "빌드 출력 디렉토리"의 경우 기본값을 사용하고 수정하지 마십시오.
10. "루트 디렉토리"는 수정하지 마십시오.
11. "환경 변수"의 경우 ">"를 클릭한 다음 "변수 추가"를 클릭합니다. 다음에 따라 정보를 입력합니다:
- node_version=20.1`.
- next_telemetry_disable=1`.
- `OPENAI_API_KEY=자신의 API 키`
- ``yarn_version=1.22.19``
- ``php_version=7.4``.
실제 필요에 따라 다음 옵션을 선택적으로 입력합니다:
- `CODE= 선택적으로 액세스 비밀번호를 입력하며 쉼표를 사용하여 여러 비밀번호를 구분할 수 있습니다`.
- `OPENAI_ORG_ID= 선택 사항, OpenAI에서 조직 ID 지정`
- `HIDE_USER_API_KEY=1 선택 사항, 사용자가 API 키를 입력하지 못하도록 합니다.
- `DISABLE_GPT4=1 옵션, 사용자가 GPT-4를 사용하지 못하도록 설정` 12.
12. "저장 후 배포"를 클릭합니다.
13. 호환성 플래그를 입력해야 하므로 "배포 취소"를 클릭합니다.
14. "빌드 설정", "기능"으로 이동하여 "호환성 플래그"를 찾습니다.
"프로덕션 호환성 플래그 구성" 및 "프리뷰 호환성 플래그 구성"에서 "nodejs_compat"를 입력합니다.
16. "배포"로 이동하여 "배포 다시 시도"를 클릭합니다.
17. 즐기세요!

View File

@ -1,228 +0,0 @@
# 常见问题
## 如何快速获得帮助?
1. 询问 ChatGPT / Bing / 百度 / Google 等。
2. 询问网友。请提供问题的背景信息和碰到问题的详细描述。高质量的提问容易获得有用的答案。
# 部署相关问题
各种部署方式详细教程参考https://rptzik3toh.feishu.cn/docx/XtrdduHwXoSCGIxeFLlcEPsdn8b
## 为什么 Docker 部署版本一直提示更新
Docker 版本相当于稳定版latest Docker 总是与 latest release version 一致,目前我们的发版频率是一到两天发一次,所以 Docker 版本会总是落后最新的提交一到两天,这在预期内。
## 如何部署在 Vercel 上
1. 注册 Github 账号fork 该项目
2. 注册 Vercel需手机验证可以用中国号码连接你的 Github 账户
3. Vercel 上新建项目,选择你在 Github fork 的项目,按需填写环境变量,开始部署。部署之后,你可以在有梯子的条件下,通过 vercel 提供的域名访问你的项目。
4. 如果需要在国内无墙访问:在你的域名管理网站,添加一条域名的 CNAME 记录,指向 cname.vercel-dns.com。之后在 Vercel 上设置你的域名访问。
## 如何修改 Vercel 环境变量
- 进入 vercel 的控制台页面;
- 选中你的 NextChat 项目;
- 点击页面头部的 Settings 选项;
- 找到侧边栏的 Environment Variables 选项;
- 修改对应的值即可。
## 环境变量 CODE 是什么?必须设置吗?
这是你自定义的访问密码,你可以选择:
1. 不设置,删除该环境变量即可。谨慎:此时任何人可以访问你的项目。
2. 部署项目时,设置环境变量 CODE支持多个密码逗号分隔。设置访问密码后用户需要在设置界面输入访问密码才可以使用。参见[相关说明](https://github.com/Yidadaa/ChatGPT-Next-Web/blob/main/README_CN.md#%E9%85%8D%E7%BD%AE%E9%A1%B5%E9%9D%A2%E8%AE%BF%E9%97%AE%E5%AF%86%E7%A0%81)
## 为什么我部署的版本没有流式响应
> 相关讨论:[#386](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/386)
如果你使用 nginx 反向代理,需要在配置文件中增加下列代码:
```
# 不缓存,支持流式输出
proxy_cache off; # 关闭缓存
proxy_buffering off; # 关闭代理缓冲
chunked_transfer_encoding on; # 开启分块传输编码
tcp_nopush on; # 开启TCP NOPUSH选项禁止Nagle算法
tcp_nodelay on; # 开启TCP NODELAY选项禁止延迟ACK算法
keepalive_timeout 300; # 设定keep-alive超时时间为65秒
```
如果你是在 netlify 部署,此问题依然等待解决,请耐心等待。
## 我部署好了,但是无法访问
请检查排除以下问题:
- 服务启动了吗?
- 端口正确映射了吗?
- 防火墙开放端口了吗?
- 到服务器的路由通吗?
- 域名正确解析了吗?
## 什么是代理,如何使用?
由于 OpenAI 的 IP 限制,中国和其他一些国家/地区无法直接连接 OpenAI API需要通过代理。你可以使用代理服务器正向代理或者已经设置好的 OpenAI API 反向代理。
- 正向代理例子科学上网梯子。docker 部署的情况下,设置环境变量 HTTP_PROXY 为你的代理地址例如10.10.10.10:8002
- 反向代理例子:可以用别人搭建的代理地址,或者通过 Cloudflare 免费设置。设置项目环境变量 BASE_URL 为你的代理地址。
## 国内服务器可以部署吗?
可以但需要解决的问题:
- 需要代理才能连接 github 和 openAI 等网站;
- 国内服务器要设置域名解析的话需要备案;
- 国内政策限制代理访问外网/ChatGPT 相关应用,可能被封。
## 为什么 docker 部署后出现网络错误?
详见讨论https://github.com/Yidadaa/ChatGPT-Next-Web/issues/1569
# 使用相关问题
## 为什么会一直提示“出错了,稍后重试吧”
原因可能有很多,请依次排查:
- 请先检查你的代码版本是否为最新版本,更新到最新版本后重试;
- 请检查 api key 是否设置正确,环境变量名称必须为全大写加下划线;
- 请检查 api key 是否可用;
- 如果经历了上述步骤依旧无法确定问题,请在 issue 区提交一个新 issue并附上 vercel 的 runtime log 或者 docker 运行时的 log。
## 为什么 ChatGPT 的回复会乱码
设置界面 - 模型设置项中,有一项为 `temperature`,如果此值大于 1那么就有可能造成回复乱码将其调回 1 以内即可。
## 使用时提示“现在是未授权状态,请在设置页输入访问密码”?
项目通过环境变量 CODE 设置了访问密码。第一次使用时,需要到设置中,输入访问码才可以使用。
## 使用时提示 "You exceeded your current quota, ..."
API KEY 有问题。余额不足。
## 使用时遇到 "Error: Loading CSS chunk xxx failed..."
为了减少首屏白屏时间,默认启用了分块编译,技术原理见下:
- https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
- https://stackoverflow.com/questions/55993890/how-can-i-disable-chunkcode-splitting-with-webpack4
- https://github.com/vercel/next.js/issues/38507
- https://stackoverflow.com/questions/55993890/how-can-i-disable-chunkcode-splitting-with-webpack4
然而 NextJS 的兼容性比较差,在比较老的浏览器上会导致此报错,可以在编译时关闭分块编译。
对于 Vercel 平台,在环境变量中增加 `DISABLE_CHUNK=1`,然后重新部署即可;
对于自行编译部署的项目,在构建时使用 `DISABLE_CHUNK=1 yarn build` 构建即可;
对于 Docker 用户,由于 Docker 打包时已经构建完毕,所以暂不支持关闭此特性。
注意,关闭此特性后,用户会在第一次访问网站时加载所有资源,如果用户网络状况较差,可能会引起较长时间的白屏,从而影响用户使用体验,所以自行考虑。
## 使用时遇到 "NotFoundError: Failed to execute 'removeChild' on 'Node': The node...."
请关闭浏览器自身的自动翻译功能,并关闭所有自动翻译插件。
# 网络服务相关问题
## Cloudflare 是什么?
CloudflareCF是一个提供 CDN域名管理静态页面托管边缘计算函数部署等的网络服务供应商。常见的用途购买和/或托管你的域名(解析、动态域名等),给你的服务器套上 CDN可以隐藏 ip 免被墙部署网站CF Pages。CF 免费提供大多数服务。
## Vercel 是什么?
Vercel 是一个全球化的云平台,旨在帮助开发人员更快地构建和部署现代 Web 应用程序。本项目以及许多 Web 应用可以一键免费部署在 Vercel 上。无需懂代码,无需懂 linux无需服务器无需付费无需设置 OpenAI API 代理。缺点是需要绑定域名才可以在国内无墙访问。
## 如何获得一个域名?
1. 自己去域名供应商处注册,国外有 Namesilo支持支付宝, Cloudflare 等等,国内有万网等等;
2. 免费的域名供应商eu.org(二级域名)等;
3. 问朋友要一个免费的二级域名。
## 如何获得一台服务器
- 国外服务器供应商举例亚马逊云谷歌云VultrBandwagonHostdare等等
国外服务器事项:服务器线路影响国内访问速度,推荐 CN2 GIA 和 CN2 线路的服务器。若服务器在国内访问困难(丢包严重等),可以尝试套 CDNCloudflare 等供应商)。
- 国内服务器供应商:阿里云,腾讯等;
国内服务器事项解析域名需要备案国内服务器带宽较贵访问国外网站Github, openAI 等)需要代理。
## 什么情况下服务器要备案?
在中国大陆经营的网站按监管要求需要备案。实际操作中,服务器位于国内且有域名解析的情况下,服务器供应商会执行监管的备案要求,否则会关停服务。通常的规则如下:
|服务器位置|域名供应商|是否需要备案|
|---|---|---|
|国内|国内|是|
|国内|国外|是|
|国外|国外|否|
|国外|国内|通常否|
换服务器供应商后需要转备案。
# OpenAI 相关问题
## 如何注册 OpenAI 账号?
去 chat.openai.com 注册。你需要:
- 一个良好的梯子OpenAI 支持地区原生 IP 地址)
- 一个支持的邮箱(例如 Gmail 或者公司/学校邮箱,非 Outlook 或 qq 邮箱)
- 接收短信认证的方式(例如 SMS-activate 网站)
## 怎么开通 OpenAI API? 怎么查询 API 余额?
官网地址需梯子https://platform.openai.com/account/usage
有网友搭建了无需梯子的余额查询代理,请询问网友获取。请鉴别来源是否可靠,以免 API Key 泄露。
## 我新注册的 OpenAI 账号怎么没有 API 余额?
4 月 6 日更新)新注册账号通常会在 24 小时后显示 API 余额。当前新注册账号赠送 5 美元余额。
## 如何给 OpenAI API 充值?
OpenAI 只接受指定地区的信用卡(中国信用卡无法使用)。一些途径举例:
1. Depay 虚拟信用卡
2. 申请国外信用卡
3. 网上找人代充
## 如何使用 GPT-4 的 API 访问?
- GPT-4 的 API 访问需要单独申请。到以下地址填写你的信息进入申请队列 waitlist准备好你的 OpenAI 组织 IDhttps://openai.com/waitlist/gpt-4-api
之后等待邮件消息。
- 开通 ChatGPT Plus 不代表有 GPT-4 权限,两者毫无关系。
## 如何使用 Azure OpenAI 接口
请参考:[#371](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/371)
## 为什么我的 Token 消耗得这么快?
> 相关讨论:[#518](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/518)
- 如果你有 GPT 4 的权限,并且日常在使用 GPT 4 api那么由于 GPT 4 价格是 GPT 3.5 的 15 倍左右,你的账单金额会急速膨胀;
- 如果你在使用 GPT 3.5,并且使用频率并不高,仍然发现自己的账单金额在飞快增加,那么请马上按照以下步骤排查:
- 去 openai 官网查看你的 api key 消费记录,如果你的 token 每小时都有消费,并且每次都消耗了上万 token那你的 key 一定是泄露了,请立即删除重新生成。**不要在乱七八糟的网站上查余额。**
- 如果你的密码设置很短,比如 5 位以内的字母,那么爆破成本是非常低的,建议你搜索一下 docker 的日志记录确认是否有人大量尝试了密码组合关键字got access code
- 通过上述两个方法就可以定位到你的 token 被快速消耗的原因:
- 如果 openai 消费记录异常,但是 docker 日志没有问题,那么说明是 api key 泄露;
- 如果 docker 日志发现大量 got access code 爆破记录,那么就是密码被爆破了。
## API 是怎么计费的?
OpenAI 网站计费说明https://openai.com/pricing#language-models
OpenAI 根据 token 数收费1000 个 token 通常可代表 750 个英文单词,或 500 个汉字。输入Prompt和输出Completion分别统计费用。
|模型|用户输入Prompt计费|模型输出Completion计费|每次交互最大 token 数|
|----|----|----|----|
|gpt-3.5-turbo|$0.0015 / 1 千 tokens|$0.002 / 1 千 tokens|4096|
|gpt-3.5-turbo-16K|$0.003 / 1 千 tokens|$0.004 / 1 千 tokens|16384|
|gpt-4|$0.03 / 1 千 tokens|$0.06 / 1 千 tokens|8192|
|gpt-4-32K|$0.06 / 1 千 tokens|$0.12 / 1 千 tokens|32768|
## gpt-3.5-turbo 和 gpt3.5-turbo-0301(或者 gpt3.5-turbo-mmdd)模型有什么区别?
官方文档说明https://platform.openai.com/docs/models/gpt-3-5
- gpt-3.5-turbo 是最新的模型,会不断得到更新。
- gpt-3.5-turbo-0301 是 3 月 1 日定格的模型快照,不会变化,预期 3 个月后被新快照替代。

View File

@ -1,191 +0,0 @@
# Frequently Asked Questions
## How to get help quickly?
1. Ask ChatGPT / Bing / Baidu / Google, etc.
2. Ask online friends. Please provide background information and a detailed description of the problem. High-quality questions are more likely to get useful answers.
# Deployment Related Questions
## Why does the Docker deployment version always prompt for updates
The Docker version is equivalent to the stable version, and the latest Docker is always consistent with the latest release version. Currently, our release frequency is once every one to two days, so the Docker version will always be one to two days behind the latest commit, which is expected.
## How to deploy on Vercel
1. Register a Github account and fork this project.
2. Register Vercel (mobile phone verification required, Chinese number can be used), and connect your Github account.
3. Create a new project on Vercel, select the project you forked on Github, fill in the required environment variables, and start deploying. After deployment, you can access your project through the domain provided by Vercel. (Requires proxy in mainland China)
- If you need to access it directly in China: At your DNS provider, add a CNAME record for the domain name, pointing to cname.vercel-dns.com. Then set up your domain access on Vercel.
## How to modify Vercel environment variables
- Enter the Vercel console page;
- Select your chatgpt-next-web project;
- Click on the Settings option at the top of the page;
- Find the Environment Variables option in the sidebar;
- Modify the corresponding values as needed.
## What is the environment variable CODE? Is it necessary to set it?
This is your custom access password, you can choose:
1. Do not set it, delete the environment variable. Be cautious: anyone can access your project at this time.
2. When deploying the project, set the environment variable CODE (supports multiple passwords, separated by commas). After setting the access password, users need to enter the access password in the settings page to use it. See [related instructions](https://github.com/Yidadaa/ChatGPT-Next-Web#access-password)
## Why doesn't the version I deployed have streaming response
> Related discussion: [#386](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/386)
If you use nginx reverse proxy, you need to add the following code to the configuration file:
```
# No caching, support streaming output
proxy_cache off; # Turn off caching
proxy_buffering off; # Turn off proxy buffering
chunked_transfer_encoding on; # Turn on chunked transfer encoding
tcp_nopush on; # Turn on TCP NOPUSH option, disable Nagle algorithm
tcp_nodelay on; # Turn on TCP NODELAY option, disable delay ACK algorithm
keepalive_timeout 300; # Set keep-alive timeout to 65 seconds
```
If you are deploying on netlify, this issue is still waiting to be resolved, please be patient.
## I've deployed, but it's not accessible
Please check and troubleshoot the following issues:
- Is the service started?
- Is the port correctly mapped?
- Is the firewall port open?
- Is the route to the server okay?
- Is the domain name resolved correctly?
## You may encounter an "Error: Loading CSS chunk xxx failed..."
To reduce the initial white screen time, Next.js enables chunking by default. You can find the technical details here:
- https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
- https://stackoverflow.com/questions/55993890/how-can-i-disable-chunkcode-splitting-with-webpack4
- https://github.com/vercel/next.js/issues/38507
- https://stackoverflow.com/questions/55993890/how-can-i-disable-chunkcode-splitting-with-webpack4
However, Next.js has limited compatibility with older browsers, which can result in this error.
You can disable chunking during building.
For Vercel platform, you can add `DISABLE_CHUNK=1` to the environment variables and redeploy.
For self-deployed projects, you can use `DISABLE_CHUNK=1 yarn build` during the build process.
For Docker users, as the build is already completed during packaging, disabling this feature is currently not supported.
Note that when you disable this feature, all resources will be loaded on the user's first visit. This may result in a longer white screen time if the user has a poor network connection, affecting the user experience. Please consider this when making a decision.
# Usage Related Questions
## Why does it always prompt "An error occurred, please try again later"
There could be many reasons, please check the following in order:
- First, check if your code version is the latest version, update to the latest version and try again;
- Check if the api key is set correctly, the environment variable name must be uppercase with underscores;
- Check if the api key is available;
- If you still cannot determine the problem after going through the above steps, please submit a new issue in the issue area and attach the runtime log of vercel or the log of docker runtime.
## Why does ChatGPT's reply get garbled
In the settings page - model settings, there is an item called `temperature`. If this value is greater than 1, it may cause garbled replies. Adjust it back to within 1.
## It prompts "Now it's unauthorized, please enter the access password on the settings page" when using?
The project has set an access password through the environment variable CODE. When using it for the first time, you need to go to settings and enter the access code to use.
## It prompts "You exceeded your current quota, ..." when using?
The API KEY is problematic. Insufficient balance.
## What is a proxy and how to use it?
Due to IP restrictions of OpenAI, China and some other countries/regions cannot directly connect to OpenAI API and need to go through a proxy. You can use a proxy server (forward proxy) or a pre-configured OpenAI API reverse proxy.
- Forward proxy example: VPN ladder. In the case of docker deployment, set the environment variable HTTP_PROXY to your proxy address (http://address:port).
- Reverse proxy example: You can use someone else's proxy address or set it up for free through Cloudflare. Set the project environment variable BASE_URL to your proxy address.
## Can I deploy it on a server in China?
It is possible but there are issues to be addressed:
- Proxy is required to connect to websites such as Github and OpenAI;
- Domain name resolution requires filing for servers in China;
- Chinese policy restricts proxy access to foreign websites/ChatGPT-related applications, which may be blocked.
# Network Service Related Questions
## What is Cloudflare?
Cloudflare (CF) is a network service provider offering CDN, domain management, static page hosting, edge computing function deployment, and more. Common use cases: purchase and/or host your domain (resolution, dynamic domain, etc.), apply CDN to your server (can hide IP to avoid being blocked), deploy websites (CF Pages). CF offers most services for free.
## What is Vercel?
Vercel is a global cloud platform designed to help developers build and deploy modern web applications more quickly. This project and many web applications can be deployed on Vercel with a single click for free. No need to understand code, Linux, have a server, pay, or set up an OpenAI API proxy. The downside is that you need to bind a domain name to access it without restrictions in China.
## How to obtain a domain name?
1. Register with a domain provider, such as Namesilo (supports Alipay) or Cloudflare for international providers, and Wanwang for domestic providers in China.
2. Free domain name providers: eu.org (second-level domain), etc.
3. Ask friends for a free second-level domain.
## How to obtain a server
- Examples of international server providers: Amazon Web Services, Google Cloud, Vultr, Bandwagon, Hostdare, etc.
International server considerations: Server lines affect access speed in China; CN2 GIA and CN2 lines are recommended. If the server has difficulty accessing in China (serious packet loss, etc.), you can try using a CDN (from providers like Cloudflare).
- Domestic server providers: Alibaba Cloud, Tencent, etc.
Domestic server considerations: Domain name resolution requires filing; domestic server bandwidth is relatively expensive; accessing foreign websites (Github, OpenAI, etc.) requires a proxy.
# OpenAI-related Questions
## How to register an OpenAI account?
Go to chat.openai.com to register. You will need:
- A good VPN (OpenAI only allows native IP addresses of supported regions)
- A supported email (e.g., Gmail or a company/school email, not Outlook or QQ email)
- A way to receive SMS verification (e.g., SMS-activate website)
## How to activate OpenAI API? How to check API balance?
Official website (requires VPN): https://platform.openai.com/account/usage
Some users have set up a proxy to check the balance without a VPN; ask online friends for access. Please verify the source is reliable to avoid API Key leakage.
## Why doesn't my new OpenAI account have an API balance?
(Updated April 6th) Newly registered accounts usually display API balance within 24 hours. New accounts are currently given a $5 balance.
## How to recharge OpenAI API?
OpenAI only accepts credit cards from designated regions (Chinese credit cards cannot be used). If the credit cards from your region is not supported, some options include:
1. Depay virtual credit card
2. Apply for a foreign credit card
3. Find someone online to top up
## How to access the GPT-4 API?
(Updated April 6th) Access to the GPT-4 API requires a separate application. Go to the following address and enter your information to join the waitlist (prepare your OpenAI organization ID): https://openai.com/waitlist/gpt-4-api
Wait for email updates afterwards.
## How to use the Azure OpenAI interface
Please refer to: [#371](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/371)
## Why is my Token consumed so fast?
> Related discussion: [#518](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/518)
- If you have GPT-4 access and use GPT-4 API regularly, your bill will increase rapidly since GPT-4 pricing is about 15 times higher than GPT-3.5;
- If you are using GPT-3.5 and not using it frequently, but still find your bill increasing fast, please troubleshoot immediately using these steps:
- Check your API key consumption record on the OpenAI website; if your token is consumed every hour and each time consumes tens of thousands of tokens, your key must have been leaked. Please delete it and regenerate it immediately. **Do not check your balance on random websites.**
- If your password is short, such as 5 characters or fewer, the cost of brute-forcing is very low. It is recommended to search docker logs to confirm whether someone has tried a large number of password combinations. Keyword: got access code
- By following these two methods, you can locate the reason for your token's rapid consumption:
- If the OpenAI consumption record is abnormal but the Docker log has no issues, it means your API key has been leaked;
- If the Docker log shows a large number of got access code brute-force attempts, your password has been cracked.

View File

@ -1,205 +0,0 @@
# Preguntas frecuentes
## ¿Cómo puedo obtener ayuda rápidamente?
1. Pregunte a ChatGPT / Bing / Baidu / Google, etc.
2. Pregunte a los internautas. Sírvase proporcionar información general sobre el problema y una descripción detallada del problema encontrado. Las preguntas de alta calidad facilitan la obtención de respuestas útiles.
# Problemas relacionados con la implementación
Referencia tutorial detallada para varios métodos de implementación: https://rptzik3toh.feishu.cn/docx/XtrdduHwXoSCGIxeFLlcEPsdn8b
## ¿Por qué la versión de implementación de Docker sigue solicitando actualizaciones?
La versión de Docker es equivalente a la versión estable, la última versión de Docker es siempre la misma que la última versión de lanzamiento, y la frecuencia de lanzamiento actual es de uno a dos días, por lo que la versión de Docker siempre se retrasará con respecto a la última confirmación de uno a dos días, lo que se espera.
## Cómo implementar en Vercel
1. Regístrese para obtener una cuenta de Github y bifurque el proyecto
2. Regístrese en Vercel (se requiere verificación de teléfono móvil, puede usar un número chino) y conéctese a su cuenta de Github
3. Cree un nuevo proyecto en Vercel, seleccione el proyecto que bifurcó en Github, complete las variables de entorno según sea necesario e inicie la implementación. Después de la implementación, puede acceder a su proyecto a través del nombre de dominio proporcionado por Vercel con una escalera.
4. Si necesitas acceder sin muros en China: En tu sitio web de administración de dominios, agrega un registro CNAME para tu nombre de dominio que apunte a cname.vercel-dns.com. Después de eso, configure el acceso a su dominio en Vercel.
## Cómo modificar las variables de entorno de Vercel
* Vaya a la página de la consola de Vercel;
* Seleccione su siguiente proyecto web chatgpt;
* Haga clic en la opción Configuración en el encabezado de la página;
* Busque la opción Variables de entorno en la barra lateral;
* Modifique el valor correspondiente.
## ¿Qué es la variable de entorno CODE? ¿Es obligatorio configurar?
Esta es su contraseña de acceso personalizada, puede elegir:
1. Si no es así, elimine la variable de entorno. Precaución: Cualquier persona puede acceder a tu proyecto en este momento.
2. Cuando implemente el proyecto, establezca la variable de entorno CODE (admite varias comas de contraseña separadas). Después de establecer la contraseña de acceso, debe ingresar la contraseña de acceso en la interfaz de configuración antes de poder usarla. Ver[Instrucciones relacionadas](https://github.com/Yidadaa/ChatGPT-Next-Web/blob/main/README_CN.md#%E9%85%8D%E7%BD%AE%E9%A1%B5%E9%9D%A2%E8%AE%BF%E9%97%AE%E5%AF%86%E7%A0%81)
## ¿Por qué la versión que implementé no transmite respuestas?
> Debates relacionados:[#386](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/386)
Si utiliza el proxy inverso nginx, debe agregar el siguiente código al archivo de configuración:
# 不缓存,支持流式输出
proxy_cache off; # 关闭缓存
proxy_buffering off; # 关闭代理缓冲
chunked_transfer_encoding on; # 开启分块传输编码
tcp_nopush on; # 开启TCP NOPUSH选项禁止Nagle算法
tcp_nodelay on; # 开启TCP NODELAY选项禁止延迟ACK算法
keepalive_timeout 300; # 设定keep-alive超时时间为65秒
Si está implementando en Netlify y este problema aún está pendiente de resolución, tenga paciencia.
## Lo implementé, pero no puedo acceder a él
Marque para descartar los siguientes problemas:
* ¿Se ha iniciado el servicio?
* ¿Los puertos están asignados correctamente?
* ¿El firewall está abriendo puertos?
* ¿Es transitable la ruta al servidor?
* ¿Se resuelve correctamente el nombre de dominio?
## ¿Qué es un proxy y cómo lo uso?
Debido a las restricciones de IP de OpenAI, China y algunos otros países no pueden conectarse directamente a las API de OpenAI y necesitan pasar por un proxy. Puede usar un servidor proxy (proxy de reenvío) o un proxy inverso de API OpenAI ya configurado.
* Ejemplo de agente positivo: escalera científica de Internet. En el caso de la implementación de Docker, establezca la variable de entorno HTTP_PROXY en su dirección proxy (por ejemplo: 10.10.10.10:8002).
* Ejemplo de proxy inverso: puede usar una dirección proxy creada por otra persona o configurarla de forma gratuita a través de Cloudflare. Establezca la variable de entorno del proyecto BASE_URL en su dirección proxy.
## ¿Se pueden implementar servidores domésticos?
Sí, pero hay que resolverlo:
* Requiere un proxy para conectarse a sitios como GitHub y openAI;
* Si el servidor doméstico desea configurar la resolución de nombres de dominio, debe registrarse;
* Las políticas nacionales restringen el acceso proxy a las aplicaciones relacionadas con Internet/ChatGPT y pueden bloquearse.
## ¿Por qué recibo un error de red después de la implementación de Docker?
Ver Discusión: https://github.com/Yidadaa/ChatGPT-Next-Web/issues/1569 para más detalles
# Problemas relacionados con el uso
## ¿Por qué sigues diciendo "Algo salió mal, inténtalo de nuevo más tarde"?
Puede haber muchas razones, por favor solucione los problemas en orden:
* Compruebe primero si la versión del código es la última versión, actualice a la última versión e inténtelo de nuevo;
* Compruebe si la clave API está configurada correctamente y si el nombre de la variable de entorno debe estar en mayúsculas y subrayado;
* Compruebe si la clave API está disponible;
* Si aún no puede identificar el problema después de los pasos anteriores, envíe un nuevo problema en el campo de problema con el registro de tiempo de ejecución de Verbel o el registro de tiempo de ejecución de Docker.
## ¿Por qué la respuesta de ChatGPT es confusa?
Interfaz de configuración: uno de los elementos de configuración del modelo es `temperature`, si este valor es mayor que 1, entonces existe el riesgo de una respuesta confusa, simplemente vuelva a llamarlo a dentro de 1.
## Al usarlo, aparece "Ahora en un estado no autorizado, ingrese la contraseña de acceso en la pantalla de configuración"?
El proyecto establece la contraseña de acceso a través de la variable de entorno CODE. Cuando lo use por primera vez, debe ingresar el código de acceso en la configuración para usarlo.
## Use el mensaje "Excedió su cuota actual, ..."
Hay un problema con la API KEY. Saldo insuficiente.
# Problemas relacionados con el servicio de red
## ¿Qué es Cloudflare?
Cloudflare (CF) es un proveedor de servicios de red que proporciona CDN, administración de nombres de dominio, alojamiento de páginas estáticas, implementación de funciones de computación perimetral y más. Usos comunes: comprar y/o alojar su nombre de dominio (resolución, nombre de dominio dinámico, etc.), poner un CDN en su servidor (puede ocultar la IP de la pared), desplegar un sitio web (CF Pages). CF ofrece la mayoría de los servicios de forma gratuita.
## ¿Qué es Vercel?
Vercel es una plataforma global en la nube diseñada para ayudar a los desarrolladores a crear e implementar aplicaciones web modernas más rápido. Este proyecto, junto con muchas aplicaciones web, se puede implementar en Vercel de forma gratuita con un solo clic. Sin código, sin Linux, sin servidores, sin tarifas, sin agente API OpenAI. La desventaja es que necesita vincular el nombre de dominio para poder acceder a él sin muros en China.
## ¿Cómo obtengo un nombre de dominio?
1. Vaya al proveedor de nombres de dominio para registrarse, hay Namesilo (soporte Alipay), Cloudflare, etc. en el extranjero, y hay Wanwang en China;
2. Proveedores de nombres de dominio gratuitos: eu.org (nombre de dominio de segundo nivel), etc.;
3. Pídale a un amigo un nombre de dominio de segundo nivel gratuito.
## Cómo obtener un servidor
* Ejemplos de proveedores de servidores extranjeros: Amazon Cloud, Google Cloud, Vultr, Bandwagon, Hostdare, etc.
Asuntos de servidores extranjeros: Las líneas de servidor afectan las velocidades de acceso nacional, se recomiendan los servidores de línea CN2 GIA y CN2. Si el servidor es de difícil acceso en China (pérdida grave de paquetes, etc.), puede intentar configurar un CDN (Cloudflare y otros proveedores).
* Proveedores de servidores nacionales: Alibaba Cloud, Tencent, etc.;
Asuntos de servidores nacionales: La resolución de nombres de dominio requiere la presentación de ICP; El ancho de banda del servidor doméstico es más caro; El acceso a sitios web extranjeros (Github, openAI, etc.) requiere un proxy.
## ¿En qué circunstancias debe grabarse el servidor?
Los sitios web que operan en China continental deben presentar de acuerdo con los requisitos reglamentarios. En la práctica, si el servidor está ubicado en China y hay resolución de nombres de dominio, el proveedor del servidor implementará los requisitos reglamentarios de presentación, de lo contrario el servicio se cerrará. Las reglas habituales son las siguientes:
|ubicación del servidor|proveedor de nombres de dominio|si se requiere la presentación|
|---|---|---|
|Doméstico|Doméstico|Sí|
|nacional|extranjero|sí|
|extranjero|extranjero|no|
|extranjero|nacional|normalmente no|
Después de cambiar de proveedor de servidores, debe transferir la presentación de ICP.
# Problemas relacionados con OpenAI
## ¿Cómo registro una cuenta OpenAI?
Vaya a chat.openai.com para registrarse. Es necesario:
* Una buena escalera (OpenAI admite direcciones IP nativas regionales)
* Un buzón compatible (por ejemplo, Gmail o trabajo/escuela, no buzón de Outlook o QQ)
* Cómo recibir autenticación por SMS (por ejemplo, sitio web de activación de SMS)
## ¿Cómo activo la API de OpenAI? ¿Cómo verifico mi saldo de API?
Dirección del sitio web oficial (se requiere escalera): https://platform.openai.com/account/usage
Algunos internautas han construido un agente de consulta de saldo sin escalera, por favor pídales a los internautas que lo obtengan. Identifique si la fuente es confiable para evitar la fuga de la clave API.
## ¿Por qué mi cuenta OpenAI recién registrada no tiene un saldo API?
(Actualizado el 6 de abril) Las cuentas recién registradas suelen mostrar el saldo de la API después de 24 horas. Se otorga un saldo de $ 5 a una cuenta recién registrada.
## ¿Cómo puedo recargar la API de OpenAI?
OpenAI solo acepta tarjetas de crédito en regiones seleccionadas (no se pueden usar tarjetas de crédito chinas). Algunos ejemplos de avenidas son:
1. Depay tarjeta de crédito virtual
2. Solicitar una tarjeta de crédito extranjera
3. Encuentra a alguien para cobrar en línea
## ¿Cómo utilizo el acceso a la API de GPT-4?
* El acceso a la API para GPT-4 requiere una solicitud independiente. Ingrese a la cola de la solicitud completando su información en la lista de espera (prepare su ID de organización OpenAI): https://openai.com/waitlist/gpt-4-api
Espere el mensaje de correo después.
* Habilitar ChatGPT Plus no significa permisos GPT-4, y los dos no tienen nada que ver entre sí.
## Uso de la interfaz de Azure OpenAI
Por favor consulte:[#371](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/371)
## ¿Por qué mi token se agota tan rápido?
> Debates relacionados:[#518](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/518)
* Si tiene permisos de GPT 4 y usa las API de GPT 4 a diario, el monto de su factura aumentará rápidamente porque el precio de GPT 4 es aproximadamente 15 veces mayor que el de GPT 3.5;
* Si está usando GPT 3.5 y no lo usa con mucha frecuencia y aún nota que su factura aumenta rápidamente, siga estos pasos para solucionar problemas ahora:
* Vaya al sitio web oficial de OpenAI para verificar sus registros de consumo de API Key, si su token se consume cada hora y se consumen decenas de miles de tokens cada vez, entonces su clave debe haberse filtrado, elimine y regenere inmediatamente.**No verifique su saldo en un sitio web desordenado.**
* Si su contraseña se acorta, como letras dentro de 5 dígitos, entonces el costo de voladura es muy bajo, se recomienda que busque en el registro de Docker para ver si alguien ha probado muchas combinaciones de contraseñas, palabra clave: got access code
* A través de los dos métodos anteriores, puede localizar la razón por la cual su token se consume rápidamente:
* Si el registro de consumo de OpenAI es anormal, pero no hay ningún problema con el registro de Docker, entonces la clave API se filtra;
* Si el registro de Docker encuentra una gran cantidad de registros de código de acceso de obtención, entonces la contraseña ha sido destruida.
## ¿Cómo se facturan las API?
Instrucciones de facturación del sitio web de OpenAI: https://openai.com/pricing#language-models\
OpenAI cobra en función del número de tokens, y 1,000 tokens generalmente representan 750 palabras en inglés o 500 caracteres chinos. Prompt y Completion cuentan los costos por separado.\
|Modelo|Facturación de entrada de usuario (aviso)|Facturación de salida del modelo (finalización)|Número máximo de tokens por interacción|
|----|----|----|----|
|gpt-3.5|$0.002 / 1 mil tokens|$0.002 / 1 mil tokens|4096|
|gpt-4|$0.03 / 1 mil tokens|$0.06 / 1 mil tokens|8192|
|gpt-4-32K|$0.06 / 1 mil tokens|$0.12 / 1 mil tokens|32768|
## ¿Cuál es la diferencia entre los modelos GPT-3.5-TURBO y GPT3.5-TURBO-0301 (o GPT3.5-TURBO-MMDD)?
Descripción de la documentación oficial: https://platform.openai.com/docs/models/gpt-3-5
* GPT-3.5-Turbo es el último modelo y se actualiza constantemente.
* GPT-3.5-turbo-0301 es una instantánea del modelo congelada el 1 de marzo, no cambiará y se espera que sea reemplazada por una nueva instantánea en 3 meses.

View File

@ -1,191 +0,0 @@
# よくある質問
## 早く助けを求めるには?
1. ChatGPT / Bing / Baidu / Google などに尋ねてください。
2. オンラインの友達に聞く。背景情報と問題の詳細な説明を提供してください。質の高い質問ほど、有益な回答を得られる可能性が高くなります。
# デプロイメントに関する質問
## なぜ Docker のデプロイバージョンは常に更新を要求するのか
Docker のバージョンは安定版と同等であり、最新の Docker は常に最新のリリースバージョンと一致しています。現在、私たちのリリース頻度は12日に1回なので、Dockerのバージョンは常に最新のコミットから12日遅れており、これは予想されることです。
## Vercel での展開方法
1. GitHub アカウントを登録し、このプロジェクトをフォークする。
2. Vercel を登録し携帯電話認証が必要、中国の番号でも可、GitHub アカウントを接続する。
3. Vercel で新規プロジェクトを作成し、GitHub でフォークしたプロジェクトを選択し、必要な環境変数を入力し、デプロイを開始する。デプロイ後、Vercel が提供するドメインからプロジェクトにアクセスできます。(中国本土ではプロキシが必要)
- 中国で直接アクセスする必要がある場合: DNS プロバイダーで、cname.vercel-dns.com を指すドメイン名の CNAME レコードを追加します。その後、Vercel でドメインアクセスを設定してください。
## Vercel 環境変数の変更方法
- Vercel のコンソールページに入ります;
- chatgpt-next-web プロジェクトを選択してください;
- ページ上部の設定オプションをクリックしてください;
- サイドバーで環境変数オプションを見つけます;
- 必要に応じて対応する値を変更してください。
## 環境変数 CODE とは何ですか?設定する必要がありますか?
カスタムアクセスパスワードです:
1. 設定しないで、環境変数を削除する。この時、誰でもあなたのプロジェクトにアクセスすることができます。
2. プロジェクトをデプロイするときに、環境変数 CODE を設定する(カンマ区切りで複数のパスワードをサポート)。アクセスパスワードを設定した後、ユーザーはそれを使用するために設定ページでアクセスパスワードを入力する必要があります。[関連手順](https://github.com/Yidadaa/ChatGPT-Next-Web#access-password)
## なぜ私がデプロイしたバージョンにはストリーミングレスポンスがないのでしょうか?
> 関連する議論: [#386](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/386)
nginx のリバースプロキシを使っている場合、設定ファイルに以下のコードを追加する必要があります:
```
# キャッシュなし、ストリーミング出力をサポート
proxy_cache off; # キャッシュをオフにする
proxy_buffering off; # プロキシバッファリングをオフにする
chunked_transfer_encoding on; # チャンク転送エンコーディングをオンにする
tcp_nopush on; # TCP NOPUSH オプションをオンにし、Nagleアルゴリズムを無効にする
tcp_nodelay on; # TCP NODELAY オプションをオンにし、遅延ACKアルゴリズムを無効にする
keepalive_timeout 300; # keep-alive のタイムアウトを 65 秒に設定する
```
netlify でデプロイしている場合、この問題はまだ解決待ちです。
## デプロイしましたが、アクセスできません。
以下の問題を確認し、トラブルシューティングを行ってください:
- サービスは開始されていますか?
- ポートは正しくマッピングされていますか?
- ファイアウォールのポートは開いていますか?
- サーバーへのルートは問題ありませんか?
- ドメイン名は正しく解決されていますか?
## "Error: Loading CSS chunk xxx failed..." と表示されることがあります。
Next.js では、最初のホワイトスクリーンの時間を短縮するために、デフォルトでチャンキングを有効にしています。技術的な詳細はこちらをご覧ください:
- https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
- https://stackoverflow.com/questions/55993890/how-can-i-disable-chunkcode-splitting-with-webpack4
- https://github.com/vercel/next.js/issues/38507
- https://stackoverflow.com/questions/55993890/how-can-i-disable-chunkcode-splitting-with-webpack4
ただし、Next.js は古いブラウザとの互換性に制限があるため、このエラーが発生することがあります。
ビルド時にチャンキングを無効にすることができます。
Vercel プラットフォームの場合は、環境変数に `DISABLE_CHUNK=1` を追加して再デプロイします。
セルフデプロイのプロジェクトでは、ビルド時に `DISABLE_CHUNK=1 yarn build` を使用することができます。
Docker ユーザーの場合、ビルドはパッケージング時にすでに完了しているため、この機能を無効にすることは現在サポートされていません。
この機能を無効にすると、ユーザーの最初の訪問時にすべてのリソースがロードされることに注意してください。その結果、ユーザーのネットワーク接続が悪い場合、ホワイト・スクリーンの時間が長くなり、ユーザーエクスペリエンスに影響を与える可能性があります。この点を考慮の上、ご判断ください。
# 使用法に関する質問
## なぜいつも "An error occurred, please try again later" と表示されるのですか?
様々な原因が考えられますので、以下の項目を順番にチェックしてみてください:
- まず、コードのバージョンが最新版かどうかを確認し、最新版にアップデートしてから再試行してください;
- api キーが正しく設定されているか確認してください。環境変数名は大文字とアンダースコアでなければなりません;
- api キーが使用可能かどうか確認する;
- 上記のステップを踏んでも問題が解決しない場合は、issue エリアに新しい issue を投稿し、vercel のランタイムログまたは docker のランタイムログを添付してください。
## ChatGPT の返信が文字化けするのはなぜですか?
設定画面-機種設定の中に `temperature` という項目があります。この値が 1 より大きい場合、返信が文字化けすることがあります。1 以内に調整してください。
## 設定ページでアクセスパスワードを入力してください」と表示される。
プロジェクトでは環境変数 CODE でアクセスパスワードを設定しています。初めて使うときは、設定ページでアクセスコードを入力する必要があります。
## 使用すると、"You exceeded your current quota, ..." と表示される。
API KEY に問題があります。残高不足です。
## プロキシとは何ですか?
OpenAI の IP 制限により、中国をはじめとする一部の国や地域では、OpenAI API に直接接続することができず、プロキシを経由する必要があります。プロキシサーバ(フォワードプロキシ)を利用するか、事前に設定された OpenAI API リバースプロキシを利用します。
- フォワードプロキシの例: VPN ラダー。docker デプロイの場合は、環境変数 HTTP_PROXY にプロキシアドレス (http://address:port) を設定します。
- リバースプロキシの例: 他人のプロキシアドレスを使うか、Cloudflare を通じて無料で設定できる。プロジェクトの環境変数 BASE_URL にプロキシアドレスを設定してください。
## 中国のサーバーにデプロイできますか?
可能ですが、対処すべき問題があります:
- GitHub や OpenAI などのウェブサイトに接続するにはプロキシが必要です;
- GitHub や OpenAI のようなウェブサイトに接続するにはプロキシが必要です;
- 中国の政策により、海外のウェブサイト/ChatGPT 関連アプリケーションへのプロキシアクセスが制限されており、ブロックされる可能性があります。
# ネットワークサービス関連の質問
## クラウドフレアとは何ですか?
CloudflareCFは、CDN、ドメイン管理、静的ページホスティング、エッジコンピューティング機能展開などを提供するネットワークサービスプロバイダーです。一般的な使用例: メインの購入やホスティング(解決、ダイナミックドメインなど)、サーバーへの CDN の適用(ブロックされないように IP を隠すことができる、ウェブサイトCF Pagesの展開。CF はほとんどのサービスを無料で提供しています。
## Vercel とは?
Vercel はグローバルなクラウドプラットフォームで、開発者がモダンなウェブアプリケーションをより迅速に構築、デプロイできるように設計されています。このプロジェクトや多くのウェブアプリケーションは、ワンクリックで Vercel 上に無料でデプロイできます。コードを理解する必要も、Linux を理解する必要も、サーバーを持つ必要も、お金を払う必要も、OpenAI API プロキシを設定する必要もありません。欠点は、中国の制限なしにアクセスするためにドメイン名をバインドする必要があることだ。
## ドメイン名の取得方法
1. Namesiloアリペイ対応や Cloudflare海外プロバイダー、Wanwang中国国内プロバイダーなどのドメインプロバイダーに登録する。
2. 無料ドメインプロバイダー: eu.orgセカンドレベルドメインなど。
3. 無料セカンドレベルドメインを友人に頼む。
## サーバーの取得方法
- 海外サーバープロバイダーの例 Amazon Web Services、Google Cloud、Vultr、Bandwagon、Hostdare など。
海外サーバーの注意点 サーバー回線は中国でのアクセス速度に影響するため、CN2 GIA、CN2 回線を推奨。もしサーバーが中国でアクセスしにくい場合深刻なパケットロスなど、CDNCloudflare のようなプロバイダーのもの)を使ってみるとよいでしょう。
- 国内のサーバープロバイダー アリババクラウド、テンセントなど
国内サーバーの注意点 ドメイン名の解決にはファイリングが必要。国内サーバーの帯域幅は比較的高い。海外のウェブサイトGitHub、OpenAI など)へのアクセスにはプロキシが必要。
# OpenAI 関連の質問
## OpenAI のアカウントを登録するには?
chat.openai.com にアクセスして登録してください。以下のものが必要です:
- 優れた VPN (OpenAI はサポートされている地域のネイティブ IP アドレスしか許可しません)
- サポートされているメール (例: Gmail や会社/学校のメール。Outlook や QQ のメールは不可)
- SMS 認証を受ける方法SMS-activate ウェブサイトなど)
## OpenAI API を有効にするにはAPI 残高の確認方法は?
公式ウェブサイトVPN が必要): https://platform.openai.com/account/usage
VPN なしで残高を確認するためにプロキシを設定しているユーザーもいます。API キーの漏洩を避けるため、信頼できる情報源であることを確認してください。
## OpenAI の新規アカウントに API 残高がないのはなぜですか?
(4月6日更新) 新規登録アカウントは通常 24 時間以内に API 残高が表示されます。現在、新規アカウントには 5 ドルの残高が与えられています。
## OpenAI API へのチャージ方法を教えてください。
OpenAI では、指定された地域のクレジットカードのみご利用いただけます(中国のクレジットカードはご利用いただけません)。お住まいの地域のクレジットカードに対応していない場合は、以下の方法があります:
1. Depay バーチャルクレジットカード
2. 海外のクレジットカードを申し込む
3. オンラインでトップアップしてくれる人を探す
## GPT-4 API にアクセスするには?
(4月6日更新) GPT-4 API へのアクセスには別途申請が必要です。以下のアドレスにアクセスし、ウェイティングリストに参加するための情報を入力してくださいOpenAI の組織 ID をご用意ください): https://openai.com/waitlist/gpt-4-api
その後、メールの更新をお待ちください。
## Azure OpenAI インターフェースの使い方
次を参照: [#371](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/371)
## トークンの消費が速いのはなぜですか?
> 関連する議論: [#518](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/518)
- GPT-4 にアクセスし、GPT-4 の API を定期的に使用している場合、GPT-4 の価格は GPT-3.5 の約 15 倍であるため、請求額が急激に増加します;
- GPT-3.5 を使用しており、頻繁に使用していないにもかかわらず、請求額が急速に増加している場合は、以下の手順で直ちにトラブルシューティングを行ってください:
- OpenAI のウェブサイトで API キーの消費記録を確認してください。トークンが 1 時間ごとに消費され、毎回数万トークンが消費される場合は、キーが流出している可能性があります。すぐに削除して再生成してください。**適当なサイトで残高を確認しないでください。**
- パスワードが 5 文字以下など短い場合、ブルートフォースによるコストは非常に低くなります。誰かが大量のパスワードの組み合わせを試したかどうかを確認するために、docker のログを検索することを推奨する。キーワード:アクセスコードの取得
- これら 2 つの方法を実行することで、トークンが急速に消費された原因を突き止めることができます:
- OpenAI の消費記録に異常があるが、Docker ログに問題がない場合、API キーが流出したことを意味します;
- Docker ログにアクセスコード取得のブルートフォース試行回数が多い場合は、パスワードがクラックされています。

View File

@ -1,230 +0,0 @@
# 자주 묻는 질문
## 어떻게 빠르게 도움을 받을 수 있나요?
1. ChatGPT / Bing / Baidu / Google 등에 질문합니다.
2. 인터넷 사용자에게 질문합니다. 문제의 배경 정보와 자세한 문제 설명을 제공하세요. 질 좋은 질문은 유용한 답변을 쉽게 받을 수 있습니다.
# 배포 관련 질문
각종 배포 방법에 대한 자세한 튜토리얼 참조: [링크](https://rptzik3toh.feishu.cn/docx/XtrdduHwXoSCGIxeFLlcEPsdn8b)
## 왜 Docker 배포 버전이 계속 업데이트 알림을 주나요?
Docker 버전은 사실상 안정된 버전과 같습니다. latest Docker는 항상 latest release version과 일치합니다. 현재 우리의 발행 빈도는 하루 또는 이틀에 한 번이므로 Docker 버전은 항상 최신 커밋보다 하루나 이틀 뒤처집니다. 이것은 예상된 것입니다.
## Vercel에서 어떻게 배포하나요?
1. Github 계정을 등록하고, 이 프로젝트를 포크합니다.
2. Vercel을 등록합니다(휴대폰 인증 필요, 중국 번호 사용 가능), Github 계정을 연결합니다.
3. Vercel에서 새 프로젝트를 생성하고, Github에서 포크한 프로젝트를 선택합니다. 환경 변수를 필요에 따라 입력한 후 배포를 시작합니다. 배포 후에는 VPN이 있는 환경에서 Vercel이 제공하는 도메인으로 프로젝트에 접근할 수 있습니다.
4. 중국에서 방화벽 없이 접근하려면: 도메인 관리 사이트에서 도메인의 CNAME 레코드를 추가하고, cname.vercel-dns.com을 가리키게 합니다. 그런 다음 Vercel에서 도메인 접근을 설정합니다.
## Vercel 환경 변수를 어떻게 수정하나요?
- Vercel의 제어판 페이지로 이동합니다.
- NextChat 프로젝트를 선택합니다.
- 페이지 상단의 Settings 옵션을 클릭합니다.
- 사이드바의 Environment Variables 옵션을 찾습니다.
- 해당 값을 수정합니다.
## 환경 변수 CODE는 무엇이며, 반드시 설정해야 하나요?
이것은 당신이 사용자 정의한 접근 비밀번호입니다. 다음 중 하나를 선택할 수 있습니다:
1. 설정하지 않습니다. 해당 환경 변수를 삭제합니다. 주의: 이 경우 누구나 프로젝트에 접근할 수 있습니다.
2. 프로젝트를 배포할 때 환경 변수 CODE를 설정합니다(여러 비밀번호는 쉼표로 구분). 접근 비밀번호를 설정하면 사용자는 설정 페이지에서 접근 비밀번호를 입력해야만 사용할 수 있습니다. [관련 설명 참조](https://github.com/Yidadaa/ChatGPT-Next-Web/blob/main/README_CN.md#%E9%85%8D%E7%BD%AE%E9%A1%B5%E9%9D%A2%E8%AE%BF%E9%97%AE%E5%AF%86%E7%A0%81)
## 왜 내 배포 버전에 스트리밍 응답이 없나요?
> 관련 토론: [#386](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/386)
nginx 리버스 프록시를 사용하는 경우, 설정 파일에 다음 코드를 추가해야 합니다:
```nginx
# 캐시하지 않고, 스트리밍 출력 지원
proxy_cache off; # 캐시 비활성화
proxy_buffering off; # 프록시 버퍼링 비활성화
chunked_transfer_encoding on; # 청크 전송 인코딩 활성화
tcp_nopush on; # TCP NOPUSH 옵션 활성화, Nagle 알고리즘 금지
tcp_nodelay on; # TCP NODELAY 옵션 활성화, 지연 ACK 알고리즘 금지
keepalive_timeout 300; # keep-alive 타임아웃을 65초로 설정
```
netlify에서 배포하는 경우, 이 문제는 아직 해결되지 않았습니다. 기다려 주십시오.
## 배포했지만 액세스할 수 없는 경우.
다음의 사항들을 확인해보세요:
- 서비스가 배포 중인가요?
- 포트가 올바르게 매핑되었나요?
- 방화벽에서 포트가 열렸나요?
- 서버 경로가 유효한가요?
- 도메인 이름이 올바른가요?
## 프록시란 무엇이며 어떻게 사용하나요?
중국 및 일부 국가에서는 OpenAI의 IP 제한으로 인해 OpenAI API에 직접 연결할 수 없으며 프록시를 거쳐야 합니다. 프록시 서버(정방향 프록시)를 사용하거나 OpenAI API에 대해 설정된 역방향 프록시를 사용할 수 있습니다.
- 정방향 프록시 예: 사이언티픽 인터넷 래더. 도커 배포의 경우 환경 변수 HTTP_PROXY를 프록시 주소(예: 10.10.10.10:8002)로 설정합니다.
- 역방향 프록시 예: 다른 사람이 구축한 프록시 주소를 사용하거나 Cloudflare를 통해 무료로 설정할 수 있습니다. 프로젝트 환경 변수 BASE_URL을 프록시 주소로 설정합니다.
## 국내 서버를 배포할 수 있나요?
예. 하지만 해결해야 할 문제가 있습니다:
- github 및 openAI와 같은 사이트에 연결하려면 프록시가 필요합니다;
- 도메인 이름 확인을 설정하려면 국내 서버를 신청해야 합니다;
- 국내 정책에 따라 프록시가 엑스트라넷/ChatGPT 관련 애플리케이션에 액세스하지 못하도록 제한되어 차단될 수 있습니다.
## 도커 배포 후 네트워크 오류가 발생하는 이유는 무엇인가요?
https://github.com/Yidadaa/ChatGPT-Next-Web/issues/1569 에서 토론을 참조하세요.
## 사용 관련 문제
## "문제가 발생했습니다, 나중에 다시 시도하세요"라는 메시지가 계속 뜨는 이유는 무엇인가요?
여러 가지 이유가 있을 수 있으니 순서대로 확인해 주세요:
- 코드 버전이 최신 버전인지 확인하고, 최신 버전으로 업데이트한 후 다시 시도해 주세요;
- API 키가 올바르게 설정되었는지 확인해주세요. 환경 변수 이름은 모두 대문자이며 밑줄이 있어야 합니다;
- API 키가 사용 가능한지 확인해 주세요;
- 위 단계를 수행한 후에도 문제를 확인할 수 없는 경우, 이슈 영역에 신규 이슈를 제출하고 버셀의 런타임 로그 또는 도커 런타임 로그를 첨부해 주시기 바랍니다.
## ChatGPT 응답이 왜곡되는 이유는 무엇인가요?
설정 - 모델 설정 섹션에 '온도'에 대한 값이 있는데, 이 값이 1보다 크면 응답이 왜곡될 수 있으니 1 이내로 다시 설정해 주세요.
## "권한이 없는 상태입니다, 설정 페이지에서 액세스 비밀번호를 입력하세요"?
프로젝트에서 환경 변수 CODE에 접근 비밀번호를 설정했습니다. 처음 사용할 때는 설정 페이지에서 액세스 코드를 입력해야 합니다.
## 사용 시 "현재 할당량을 초과했습니다, ..."라는 메시지가 표시됩니다.
API 키에 문제가 있습니다. 잔액이 부족합니다.
## "오류: CSS 청크 xxx를 로드하지 못했습니다..."와 함께 사용.
첫 번째 화이트 스크린 시간을 줄이기 위해 청크 컴파일이 기본적으로 활성화되어 있으며, 기술 원칙은 아래를 참조하세요:
- https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
- https://stackoverflow.com/questions/55993890/how-can-i-disable-chunkcode-splitting-with-webpack4
- https://github.com/vercel/next.js/issues/38507
- https://stackoverflow.com/questions/55993890/how-can-i-disable-chunkcode-splitting-with-webpack4
그러나 NextJS는 호환성이 좋지 않아 구형 브라우저에서 이 오류가 발생할 수 있으므로 컴파일 시 청크 컴파일을 비활성화할 수 있습니다.
버셀 플랫폼의 경우 환경 변수에 `DISABLE_CHUNK=1`을 추가하고 다시 배포합니다;
자체 컴파일 및 배포한 프로젝트의 경우, 빌드 시 `DISABLE_CHUNK=1 yarn build`를 사용하여 빌드합니다;
Docker 사용자의 경우, Docker가 프로젝트를 패키징할 때 이미 빌드하기 때문에 이 기능을 해제하는 것은 지원되지 않습니다.
이 기능을 끄면 사용자가 웹사이트를 처음 방문할 때 모든 리소스를 로드하므로 인터넷 연결 상태가 좋지 않은 경우 흰색 화면이 길게 표시되어 사용자 경험에 영향을 줄 수 있으므로 사용자가 직접 고려하시기 바랍니다.
"## NotFoundError: '노드': 노드....에서 'removeChild'를 실행하지 못했습니다." 오류가 발생했습니다.
브라우저의 자체 자동 번역 기능을 비활성화하고 모든 자동 번역 플러그인을 닫아주세요.
## 웹 서비스 관련 문제
## 클라우드플레어란 무엇인가요?
Cloudflare(CF)는 CDN, 도메인 관리, 정적 페이지 호스팅, 엣지 컴퓨팅 기능 배포 등을 제공하는 웹 서비스 제공업체입니다. 일반적인 용도: 도메인 구매 및/또는 호스팅(리졸브, 동적 도메인 등), 서버에 CDN 설치(벽에서 IP를 숨기는 기능), 웹사이트 배포(CF 페이지). CF는 이러한 서비스 대부분을 무료로 제공합니다.
## Vercel이란 무엇인가요?
Vercel은 개발자가 최신 웹 애플리케이션을 더 빠르게 빌드하고 배포할 수 있도록 설계된 글로벌 클라우드 플랫폼입니다. 이 프로젝트와 많은 웹 애플리케이션을 클릭 한 번으로 Vercel에 무료로 배포할 수 있습니다. 코드, 리눅스, 서버, 수수료가 필요 없고 OpenAI API 프록시를 설정할 필요도 없습니다. 단점은 중국에서 장벽 없이 액세스하려면 도메인 이름을 바인딩해야 한다는 것입니다.
## 도메인 네임은 어떻게 얻나요?
1) 도메인 네임 공급업체로 이동하여 해외에서는 Namesilo(알리페이 지원), 클라우드플레어 등, 중국에서는 월드와이드웹과 같은 도메인 네임을 등록합니다. 2) 무료 도메인 네임 공급업체: 예: eBay;
2. 무료 도메인 네임 제공업체: eu.org(두 번째 레벨 도메인 네임) 등..;
3. 친구에게 무료 2단계 도메인 네임을 요청합니다.
## 서버를 얻는 방법
- 외국 서버 제공업체의 예: 아마존 클라우드, 구글 클라우드, 벌터, 밴드왜건, 호스트데어 등;
해외 서버 문제: 서버 라인은 해당 국가의 액세스 속도에 영향을 미치므로 CN2 GIA 및 CN2 라인 서버를 권장합니다. 국내 서버의 접속에 문제가 있는 경우(심각한 패킷 손실 등) CDN(Cloudflare 및 기타 제공 업체)을 설정해 볼 수 있습니다.
- 국내 서버 제공업체: 알리윈, 텐센트 등;
국내 서버 문제: 도메인 이름 확인을 신청해야 하며, 국내 서버 대역폭이 더 비싸고, 해외 사이트(Github, openAI 등)에 액세스하려면 프록시가 필요합니다.
## 서버는 언제 신청해야 하나요?
중국 본토에서 운영되는 웹사이트는 규제 요건에 따라 신고해야 합니다. 실제로 서버가 중국에 있고 도메인 네임 레졸루션이 있는 경우 서버 제공업체가 규제 신고 요건을 시행하며, 그렇지 않으면 서비스가 종료됩니다. 일반적인 규칙은 다음과 같습니다:
|서버 위치|도메인 네임 공급자|파일링 필요 여부|
|---|---|---|
|국내|국내|예
|국내|외국|예
|외국|외국인|아니요
|외국|국내|일반적으로 아니요|
서버 공급자를 전환한 후 파일링을 전환해야 합니다.
## OpenAI 관련 질문
## OpenAI 계정은 어떻게 가입하나요?
chat.openai.com으로 이동하여 등록하세요. 다음이 필요합니다:
- 유효한 래더(OpenAI는 지역별 기본 IP 주소를 지원합니다)
- 지원되는 이메일 주소(예: Outlook이나 qq가 아닌 Gmail 또는 회사/학교 이메일)
- SMS 인증을 받을 수 있는 방법(예: SMS 활성화 웹사이트)
## OpenAI API는 어떻게 열 수 있나요? API 잔액은 어떻게 확인하나요?
공식 웹사이트 주소(래더 필요): https://platform.openai.com/account/usage
일부 사용자는 래더 없이 잔액 조회 에이전트를 구축한 경우가 있으니, 해당 사용자에게 요청해 주시기 바랍니다. API 키 유출을 방지하기 위해 신뢰할 수 있는 소스인지 확인하시기 바랍니다.
## 새로 등록한 OpenAI 계정에 API 잔액이 없는 이유는 무엇인가요?
(4월 6일 업데이트) 새로 등록된 계정은 일반적으로 24시간 후에 API 잔액이 표시됩니다. 현재 새로 등록된 계정에는 $5의 잔액이 표시됩니다.
## OpenAI API를 충전하려면 어떻게 해야 하나요?
OpenAI는 특정 지역의 신용카드만 사용할 수 있습니다(중국 신용카드는 사용할 수 없음). 충전 방법의 몇 가지 예는 다음과 같습니다:
1. 가상 신용카드로 결제하기
2. 해외 신용카드 신청
3. 온라인에서 신용카드를 충전할 사람 찾기
## GPT-4 API 액세스는 어떻게 사용하나요?
- GPT-4 API 액세스는 별도의 신청이 필요합니다. 다음 주소로 이동하여 정보를 입력하여 신청 대기열 대기자 명단에 들어가세요(OpenAI 조직 ID를 준비하세요): https://openai.com/waitlist/gpt-4-api.
그런 다음 이메일 메시지를 기다립니다.
- ChatGPT Plus를 사용하도록 설정했다고 해서 GPT-4 권한이 있는 것은 아니며, 서로 관련이 없습니다.
## Azure OpenAI 인터페이스 사용 방법
참조: [#371](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/371)
## 내 토큰이 왜 이렇게 빨리 소모되나요?
> 관련 토론: [#518](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/518)
- GPT 4에 액세스 권한이 있고 매일 GPT 4 API를 사용하는 경우, GPT 4 가격이 GPT 3.5의 약 15배이기 때문에 청구 금액이 급격히 증가합니다;
- GPT 3.5를 자주 사용하지 않는데도 요금이 급격하게 증가하는 경우 아래 단계를 따라 확인하시기 바랍니다:
- 오픈아이 공식 웹사이트로 이동하여 API 키 소비 기록을 확인하고, 매 시간마다 토큰이 소비되고 매번 수만 개의 토큰이 소비된다면 키가 유출된 것이므로 즉시 삭제하고 재생성하시기 바랍니다. 즉시 키를 삭제하고 다시 생성하시기 바랍니다. 지저분한 웹사이트에서 잔액을 확인하지 마세요. **
- 비밀번호 설정이 5자리 이내의 문자와 같이 매우 짧으면 블라스팅 비용이 매우 낮습니다. 도커의 로그 기록을 검색하여 누군가 많은 수의 비밀번호 조합을 시도했는지 확인하는 것이 좋습니다. 키워드: 액세스 코드를 얻었습니다.
- 이 두 가지 방법을 사용하면 토큰이 소비되는 이유를 빠르게 찾을 수 있습니다:
- 오픈아이 소비 기록은 비정상적이지만 도커 로그는 정상이라면 API 키가 유출되고 있다는 뜻입니다;
- 도커 로그에서 액세스 코드 버스트 레코드가 많이 발견되면 비밀번호가 버스트된 것입니다.
## API의 가격은 어떻게 청구되나요?
OpenAI의 청구 지침은 https://openai.com/pricing#language-models 에서 확인할 수 있습니다.
OpenAI는 토큰 수에 따라 요금을 청구하며, 일반적으로 1000토큰은 영어 단어 750개 또는 중국어 문자 500개를 나타냅니다. 입력(프롬프트)과 출력(완료)은 별도로 청구됩니다.
|모델|사용자 입력(프롬프트) 청구 |모델 출력(완료) 청구 |인터랙션당 최대 토큰 수 |
|----|----|----|----|
|GPT-3.5-TURBO|$0.0015 / 1천 토큰|$0.002 / 1천 토큰|4096|
|GPT-3.5-TURBO-16K|$0.003 / 1천 토큰|$0.004 / 1천 토큰|16384| |GPT-4|$0.004 / 1천 토큰|16384
|GPT-3.5-TURBO-16K|$0.003 / 1천 토큰|$0.004 / 1천 토큰|16384| |GPT-4|$0.03 / 1천 토큰|$0.06 / 1천 토큰|8192
|GPT-4-32K|$0.06 / 1천 토큰|$0.12 / 1천 토큰|32768|
## gpt-3.5-터보와 gpt3.5-터보-0301(또는 gpt3.5-터보-mmdd) 모델의 차이점은 무엇인가요?
공식 문서 설명: https://platform.openai.com/docs/models/gpt-3-5
- GPT-3.5-TURBO는 최신 모델이며 지속적으로 업데이트될 예정입니다.
- gpt-3.5-turbo-0301은 3월 1일에 고정된 모델의 스냅샷으로, 변경되지 않으며 3개월 후에 새로운 스냅샷으로 대체될 예정입니다.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 MiB

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="30" height="30" fill="none" viewBox="0 0 30 30"><defs><rect id="path_0" width="30" height="30" x="0" y="0"/><rect id="path_1" width="20.455" height="20.455" x="0" y="0"/></defs><g opacity="1" transform="translate(0 0) rotate(0 14.999999999999998 14.999999999999998)"><rect width="30" height="30" x="0" y="0" fill="#E7F8FF" opacity="1" rx="10" transform="translate(0 0) rotate(0 14.999999999999998 14.999999999999998)"/><mask id="bg-mask-0" fill="#fff"><use xlink:href="#path_0"/></mask><g mask="url(#bg-mask-0)"><g opacity="1" transform="translate(4.772727272727272 4.772727272727273) rotate(0 10.227272727272725 10.227272727272725)"><mask id="bg-mask-1" fill="#fff"><use xlink:href="#path_1"/></mask><g mask="url(#bg-mask-1)"><path id="分组 1" fill-rule="evenodd" style="fill:#1f948c" d="M19.11 8.37L19.11 8.37C19.28 7.85 19.37 7.31 19.37 6.76C19.37 5.86 19.13 4.97 18.66 4.19C17.73 2.59 16 1.6 14.13 1.6C13.76 1.6 13.4 1.64 13.04 1.71C12.06 0.62 10.65 0 9.17 0L9.14 0L9.13 0C6.86 0 4.86 1.44 4.16 3.57C2.7 3.86 1.44 4.76 0.71 6.04C0.24 6.83 0 7.72 0 8.63C0 9.9 0.48 11.14 1.35 12.08C1.17 12.6 1.08 13.15 1.08 13.69C1.08 14.6 1.33 15.49 1.79 16.27C2.92 18.21 5.2 19.21 7.42 18.74C8.4 19.83 9.8 20.45 11.28 20.45L11.31 20.45L11.33 20.45C13.59 20.45 15.6 19.01 16.3 16.88C17.76 16.59 19.01 15.69 19.75 14.41C20.21 13.63 20.45 12.74 20.45 11.83C20.45 10.55 19.97 9.32 19.11 8.37Z M8.94734 18.1579C8.90734 18.1879 8.86734 18.2079 8.82734 18.2279C9.52734 18.8079 10.3973 19.1179 11.3073 19.1179L11.3173 19.1179C13.4573 19.1179 15.1973 17.3979 15.1973 15.2879L15.1973 10.5279C15.1973 10.5079 15.1773 10.4879 15.1573 10.4779L13.4173 9.48792L13.4173 15.2379C13.4173 15.4679 13.2873 15.6879 13.0773 15.8079L8.94734 18.1579Z M8.27654 17.0048L12.4465 14.6248C12.4665 14.6148 12.4765 14.5948 12.4765 14.5748L12.4765 14.5748L12.4765 12.5848L7.43654 15.4548C7.22654 15.5748 6.96654 15.5748 6.75654 15.4548L2.62654 13.1048C2.58654 13.0848 2.53654 13.0448 2.50654 13.0348C2.46654 13.2448 2.44654 13.4648 2.44654 13.6848C2.44654 14.3548 2.62654 15.0148 2.96654 15.6048L2.96654 15.5948C3.66654 16.7848 4.94654 17.5148 6.33654 17.5148C7.01654 17.5148 7.68654 17.3348 8.27654 17.0048Z M3.90324 5.16818C3.90324 5.12818 3.90324 5.06818 3.90324 5.02818C3.05324 5.33818 2.33324 5.92818 1.88324 6.70818L1.88324 6.70818C1.54324 7.28818 1.36324 7.94818 1.36324 8.61818C1.36324 9.98818 2.10324 11.2582 3.30324 11.9482L7.47324 14.3182C7.49324 14.3282 7.51324 14.3282 7.53324 14.3182L9.28324 13.3182L4.24324 10.4482C4.03324 10.3382 3.90324 10.1182 3.90324 9.87818L3.90324 9.87818L3.90324 5.16818Z M17.1561 8.50521L12.9761 6.1252C12.9561 6.1252 12.9361 6.1252 12.9161 6.1352L11.1761 7.1252L16.2161 9.9952C16.4261 10.1152 16.5561 10.3352 16.5561 10.5752C16.5561 10.5752 16.5561 10.5752 16.5561 10.5752L16.5561 15.4252C18.0761 14.8652 19.0961 13.4352 19.0961 11.8252C19.0961 10.4552 18.3561 9.1952 17.1561 8.50521Z M8.01418 5.82927C7.99418 5.83927 7.98418 5.85927 7.98418 5.87927L7.98418 5.87927L7.98418 7.86927L13.0242 4.99927C13.1242 4.93927 13.2442 4.90927 13.3642 4.90927C13.4842 4.90927 13.5942 4.93927 13.7042 4.99927L17.8342 7.34927C17.8742 7.36927 17.9142 7.39927 17.9542 7.41927L17.9542 7.41927C17.9842 7.20927 18.0042 6.98927 18.0042 6.76927C18.0042 4.65927 16.2642 2.93927 14.1242 2.93927C13.4442 2.93927 12.7742 3.11927 12.1842 3.44927L8.01418 5.82927Z M9.14676 1.33731C6.99676 1.33731 5.25676 3.05731 5.25676 5.16731L5.25676 9.92731C5.25676 9.94731 5.27676 9.95731 5.28676 9.96731L7.03676 10.9673L7.03676 5.22731L7.03676 5.21731C7.03676 4.98731 7.16676 4.76731 7.37676 4.64731L11.5068 2.29731C11.5468 2.26731 11.5968 2.23731 11.6268 2.22731C10.9268 1.64731 10.0468 1.33731 9.14676 1.33731Z M7.98345 11.5093L10.2235 12.7793L12.4735 11.5093L12.4735 8.9493L10.2235 7.6693L7.98345 8.9493L7.98345 11.5093Z" opacity="1" transform="translate(0 0) rotate(0 10.227272727272725 10.227272727272725)"/></g></g></g></g></svg>

Before

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

View File

@ -1,31 +0,0 @@
# 同步聊天记录
## 准备工作
- GitHub账号
- 拥有自己搭建过的ChatGPT-Next-Web的服务器
- [UpStash](https://upstash.com)
## 开始教程
1. 注册UpStash账号
2. 创建数据库
![注册登录](./images/upstash-1.png)
![创建数据库](./images/upstash-2.png)
![选择服务器](./images/upstash-3.png)
3. 找到REST API分别复制UPSTASH_REDIS_REST_URL和UPSTASH_REDIS_REST_TOKEN⚠切记⚠不要泄露Token!
![复制](./images/upstash-4.png)
4. UPSTASH_REDIS_REST_URL和UPSTASH_REDIS_REST_TOKEN复制到你的同步配置点击**检查可用性**
![同步1](./images/upstash-5.png)
如果没什么问题,那就成功了
![同步可用性完成的样子](./images/upstash-6.png)
5. Success!
![好耶~](./images/upstash-7.png)

View File

@ -1,31 +0,0 @@
# Synchronize Chat Logs with UpStash
## Prerequisites
- GitHub account
- Your own ChatGPT-Next-Web server set up
- [UpStash](https://upstash.com)
## Getting Started
1. Register for an UpStash account.
2. Create a database.
![Register and Login](./images/upstash-1.png)
![Create Database](./images/upstash-2.png)
![Select Server](./images/upstash-3.png)
3. Find the REST API and copy UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN (⚠Important⚠: Do not share your token!)
![Copy](./images/upstash-4.png)
4. Copy UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN into your synchronization configuration, then click **Check Availability**.
![Synchronize 1](./images/upstash-5.png)
If everything is in order, you've successfully completed this step.
![Sync Availability Check Completed](./images/upstash-6.png)
5. Success!
![Great job~!](./images/upstash-7.png)

View File

@ -1,31 +0,0 @@
# Sincronizzare i Log delle Chat con UpStash
## Prerequisiti
- Account GitHub
- Server ChatGPT-Next-Web di propria configurazione
- [UpStash](https://upstash.com)
## Per iniziare
1. Registrarsi per un account UpStash.
2. Creare un database.
![Registrarsi ed Accedere](./images/upstash-1.png)
![Creare un Database](./images/upstash-2.png)
![Selezionare il Server](./images/upstash-3.png)
3. Trovare l'API REST e copiare UPSTASH_REDIS_REST_URL e UPSTASH_REDIS_REST_TOKEN (⚠Importante⚠: Non condividere il token!)
![Copia](./images/upstash-4.png)
4. Copiare UPSTASH_REDIS_REST_URL e UPSTASH_REDIS_REST_TOKEN nella configurazione di sincronizzazione, quindi fare clic su **Verifica la Disponibilità**.
![Sincronizzazione 1](./images/upstash-5.png)
Se tutto è in ordine, hai completato con successo questa fase.
![Verifica la Disponibilità della Sincronizzazione Completata](./images/upstash-6.png)
5. Successo!
![Ottimo lavoro~!](./images/upstash-7.png)

View File

@ -1,31 +0,0 @@
# UpStashを使用してチャットログを同期する
## 事前準備
- GitHubアカウント
- 自分自身でChatGPT-Next-Webのサーバーをセットアップしていること
- [UpStash](https://upstash.com)
## 始める
1. UpStashアカウントを登録します。
2. データベースを作成します。
![登録とログイン](./images/upstash-1.png)
![データベースの作成](./images/upstash-2.png)
![サーバーの選択](./images/upstash-3.png)
3. REST APIを見つけ、UPSTASH_REDIS_REST_URLとUPSTASH_REDIS_REST_TOKENをコピーします⚠重要⚠トークンを共有しないでください
![コピー](./images/upstash-4.png)
4. UPSTASH_REDIS_REST_URLとUPSTASH_REDIS_REST_TOKENを同期設定にコピーし、次に「可用性を確認」をクリックします。
![同期1](./images/upstash-5.png)
すべてが正常であれば、このステップは成功です。
![同期可用性チェックが完了しました](./images/upstash-6.png)
5. 成功!
![お疲れ様でした~](./images/upstash-7.png)

View File

@ -1,31 +0,0 @@
# UpStash를 사용하여 채팅 기록 동기화
## 사전 준비물
- GitHub 계정
- 자체 ChatGPT-Next-Web 서버 설정
- [UpStash](https://upstash.com)
## 시작하기
1. UpStash 계정 등록
2. 데이터베이스 생성
![등록 및 로그인](./images/upstash-1.png)
![데이터베이스 생성](./images/upstash-2.png)
![서버 선택](./images/upstash-3.png)
3. REST API를 찾아 UPSTASH_REDIS_REST_URL 및 UPSTASH_REDIS_REST_TOKEN을 복사합니다 (⚠주의⚠: 토큰을 공유하지 마십시오!)
![복사](./images/upstash-4.png)
4. UPSTASH_REDIS_REST_URL 및 UPSTASH_REDIS_REST_TOKEN을 동기화 구성에 복사한 다음 **가용성 확인**을 클릭합니다.
![동기화 1](./images/upstash-5.png)
모든 것이 정상인 경우,이 단계를 성공적으로 완료했습니다.
![동기화 가용성 확인 완료](./images/upstash-6.png)
5. 성공!
![잘 했어요~!](./images/upstash-7.png)

View File

@ -1,12 +0,0 @@
# How to add a new translation?
Assume that we are adding a new translation for `new`.
1. copy `app/locales/en.ts` to `app/locales/new.ts`;
2. edit `new.ts`, change `const en: LocaleType = ` to `const new: PartialLocaleType`, and `export default new;`;
3. edit `app/locales/index.ts`:
4. `import new from './new.ts'`;
5. add `new` to `ALL_LANGS`;
6. add `new: "new lang"` to `ALL_LANG_OPTIONS`;
7. translate the strings in `new.ts`;
8. submit a pull request, and the author will merge it.

View File

@ -1,101 +0,0 @@
# 用户手册 User Manual
> No english version yet, please read this doc with ChatGPT or other translation tools.
本文档用于解释 NextChat 的部分功能介绍和设计原则。
## 面具 (Mask)
### 什么是面具?它和提示词的区别是什么?
面具 = 多个预设提示词 + 模型设置 + 对话设置。
其中预设提示词Contextual Prompts一般用于 In-Context Learning用于让 ChatGPT 生成更加符合要求的输出,也可以增加系统约束或者输入有限的额外知识。
模型设置则顾名思义,使用此面具创建的对话都会默认使用对应的模型参数。
对话设置是与对话体验相关的一系列设置,我们会在下方的章节中依次介绍。
### 如何添加一个预设面具?
目前仅能够通过编辑源代码的方式添加预设面具,请根据需要编辑 [mask](../app/masks/) 目录下对应语言的文件即可。
编辑步骤如下:
1. 在 NextChat 中配置好一个面具;
2. 使用面具编辑页面的下载按钮,将面具保存为 JSON 格式;
3. 让 ChatGPT 帮你将 json 文件格式化为对应的 ts 代码;
4. 放入对应的 .ts 文件。
后续会增加使用旁加载的方式加载面具。
## 对话 (Chat)
### 对话框上方的按钮的作用
在默认状态下,将鼠标移动到按钮上,即可查看按钮的文字说明,我们依次介绍:
- 对话设置:当前对话的设置,它与全局设置的关系,请查看下一小节的说明;
- 颜色主题:点击即可在自动、暗黑、浅色之间轮换;
- 快捷指令:项目内置的快捷填充预设提示词,也可以在对话框中输入 / 进行搜索;
- 所有面具:进入面具页面;
- 清除聊天:插入一个清除标记,标记上方的聊天将不会发给 GPT效果相当于清除了当前对话当然你也可以再次点击该按钮可取消清除
- 模型设置:更改当前对话的模型,注意,此按钮只会修改当前对话的模型,并不会修改全局默认模型。
### 对话内设置与全局设置的关系
目前有两处设置入口:
1. 页面左下角的设置按钮,进入后是全局设置页;
2. 对话框上方的设置按钮,进入后是对话设置页。
在新建对话后,该对话的设置默认与全局设置保持同步,修改全局设置,则新建对话的对话内设置也会被同步修改。
一旦用户手动更改过对话内设置,则对话内设置将与全局设置断开同步,此时更改全局设置,将不会对该对话生效。
如果想恢复两者的同步关系,可以将“对话内设置 -> 使用全局设置”选项勾选。
### 对话内设置项的含义
点开对话框上方的按钮,进入对话内设置,内容从上到下依次为:
- 预设提示词列表:可以增加、删除、排序预设提示词
- 角色头像:顾名思义
- 角色名称:顾名思义
- 隐藏预设对话:隐藏后,预设提示词不会出现在聊天界面
- 使用全局设置:用于表示当前对话是否使用全局对话设置
- 模型设置选项:剩余的选项与全局设置选项含义一致,见下一小节
### 全局设置项的含义
- model / temperature / top_p / max_tokens / presence_penalty / frequency_penalty 均为 ChatGPT 的设置参数,详情请查阅 OpenAI 官方文档,再次不再赘述;
- 注入系统级提示信息、用户输入预处理:详情请看 [https://github.com/Yidadaa/ChatGPT-Next-Web/issues/2144](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/2144)
- 附带历史消息数:用户每次输入消息并发送时,所携带的最近 n 条消息数量;
- 历史消息长度压缩阈值:当已经产生的聊天字数达到该数值以后,则自动触发历史摘要功能;
- 历史摘要:是否启用历史摘要功能。
### 什么是历史摘要?
历史摘要功能,也是历史消息压缩功能,是保证长对话场景下保持历史记忆的关键,合理使用该功能可以在不丢失历史话题信息的情况下,节省所使用的 token。
由于 ChatGPT API 的长度限制,我们以 3.5 模型为例,它只能接受小于 4096 tokens 的对话消息,一旦超出这个数值,就会报错。
同时为了让 ChatGPT 理解我们对话的上下文,往往会携带多条历史消息来提供上下文信息,而当对话进行一段时间之后,很容易就会触发长度限制。
为了解决此问题,我们增加了历史记录压缩功能,假设阈值为 1000 字符,那么每次用户产生的聊天记录超过 1000 字符时,都会将没有被总结过的消息,发送给 ChatGPT让其产生一个 100 字所有的摘要。
这样,历史信息就从 1000 字压缩到了 100 字,这是一种有损压缩,但已能满足大多数使用场景。
### 什么时候应该关闭历史摘要?
历史摘要可能会影响 ChatGPT 的对话质量,所以如果对话场景是翻译、信息提取等一次性对话场景,请直接关闭历史摘要功能,并将历史消息数设置为 0。
### 当用户发送一条消息时,有哪些信息被发送出去了?
当用户在对话框输入了一条消息后,发送给 ChatGPT 的消息,包含以下几个部分:
1. 系统级提示词:用于尽可能贴近 ChatGPT 官方 WebUI 的使用体验,可在设置中关闭此信息;
2. 历史摘要:作为长期记忆,提供长久但模糊的上下文信息;
3. 预设提示词:当前对话内设置的预设提示词,用于 In-Context Learning 或者注入系统级限制;
4. 最近 n 条对话记录:作为短期记忆,提供短暂但精确的上下文信息;
5. 用户当前输入的消息。

View File

@ -1,39 +0,0 @@
# Vercel 的使用说明
## 如何新建项目
当你从 Github fork 本项目之后,需要重新在 Vercel 创建一个全新的 Vercel 项目来重新部署,你需要按照下列步骤进行。
![vercel-create-1](./images/vercel/vercel-create-1.jpg)
1. 进入 Vercel 控制台首页;
2. 点击 Add New
3. 选择 Project。
![vercel-create-2](./images/vercel/vercel-create-2.jpg)
1. 在 Import Git Repository 处,搜索 chatgpt-next-web
2. 选中新 fork 的项目,点击 Import。
![vercel-create-3](./images/vercel/vercel-create-3.jpg)
1. 在项目配置页,点开 Environmane Variables 开始配置环境变量;
2. 依次新增名为 OPENAI_API_KEY 和 CODE ([访问密码](https://github.com/Yidadaa/ChatGPT-Next-Web/blob/357296986609c14de10bf210871d30e2f67a8784/docs/faq-cn.md#%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F-code-%E6%98%AF%E4%BB%80%E4%B9%88%E5%BF%85%E9%A1%BB%E8%AE%BE%E7%BD%AE%E5%90%97)) 的环境变量;
3. 填入环境变量对应的值;
4. 点击 Add 确认增加环境变量;
5. 请确保你添加了 OPENAI_API_KEY否则无法使用
6. 点击 Deploy创建完成耐心等待 5 分钟左右部署完成。
## 如何增加自定义域名
[TODO]
## 如何更改环境变量
![vercel-env-edit](./images/vercel/vercel-env-edit.jpg)
1. 进去 Vercel 项目内部控制台,点击顶部的 Settings 按钮;
2. 点击左侧的 Environment Variables
3. 点击已有条目的右侧按钮;
4. 选择 Edit 进行编辑,然后保存即可。
⚠️️ 注意:每次修改完环境变量,你都需要[重新部署项目](#如何重新部署)来让改动生效!
## 如何重新部署
![vercel-redeploy](./images/vercel/vercel-redeploy.jpg)
1. 进入 Vercel 项目内部控制台,点击顶部的 Deployments 按钮;
2. 选择列表最顶部一条的右侧按钮;
3. 点击 Redeploy 即可重新部署。

View File

@ -1,48 +0,0 @@
# Instrucciones de uso de Verbel
## Cómo crear un nuevo proyecto
Cuando bifurca este proyecto desde Github y necesita crear un nuevo proyecto de Vercel en Vercel para volver a implementarlo, debe seguir los pasos a continuación.
![vercel-create-1](./images/vercel/vercel-create-1.jpg)
1. Vaya a la página de inicio de la consola de Vercel;
2. Haga clic en Agregar nuevo;
3. Seleccione Proyecto.
![vercel-create-2](./images/vercel/vercel-create-2.jpg)
1. En Import Git Repository, busque chatgpt-next-web;
2. Seleccione el proyecto de la nueva bifurcación y haga clic en Importar.
![vercel-create-3](./images/vercel/vercel-create-3.jpg)
1. En la página de configuración del proyecto, haga clic en Variables de entorno para configurar las variables de entorno;
2. Agregar variables de entorno denominadas OPENAI_API_KEY y CODE;
3. Rellenar los valores correspondientes a las variables de entorno;
4. Haga clic en Agregar para confirmar la adición de variables de entorno;
5. Asegúrese de agregar OPENAI_API_KEY, de lo contrario no funcionará;
6. Haga clic en Implementar, créelo y espere pacientemente unos 5 minutos a que se complete la implementación.
## Cómo agregar un nombre de dominio personalizado
\[TODO]
## Cómo cambiar las variables de entorno
![vercel-env-edit](./images/vercel/vercel-env-edit.jpg)
1. Vaya a la consola interna del proyecto Vercel y haga clic en el botón Configuración en la parte superior;
2. Haga clic en Variables de entorno a la izquierda;
3. Haga clic en el botón a la derecha de una entrada existente;
4. Seleccione Editar para editarlo y, a continuación, guárdelo.
⚠️️ Nota: Lo necesita cada vez que modifique las variables de entorno[Volver a implementar el proyecto](#如何重新部署)para que los cambios surtan efecto!
## Cómo volver a implementar
![vercel-redeploy](./images/vercel/vercel-redeploy.jpg)
1. Vaya a la consola interna del proyecto Vercel y haga clic en el botón Implementaciones en la parte superior;
2. Seleccione el botón derecho del artículo superior de la lista;
3. Haga clic en Volver a implementar para volver a implementar.

View File

@ -1,48 +0,0 @@
# Vercel 使用説明書
## 新規プロジェクトの作成方法
このプロジェクトを GitHub からフォークし、Vercel で新しい Vercel プロジェクトを作成して再デプロイする必要がある場合は、以下の手順に従ってください。
![vercel-create-1](./images/vercel/vercel-create-1.jpg)
1. Vercel コンソールのホームページにアクセスします;
2. 新規追加をクリックする;
3. プロジェクトを選択します。
![vercel-create-2](./images/vercel/vercel-create-2.jpg)
1. Git リポジトリのインポートで、chatgpt-next-web を検索します;
2 .新しいフォークプロジェクトを選択し、インポートをクリックします。
![vercel-create-3](./images/vercel/vercel-create-3.jpg)
1. Project Settings ページで、Environment Variables をクリックして環境変数を設定する;
2. OPENAI_API_KEY と CODE という名前の環境変数を追加します;
3. 環境変数に対応する値を入力します;
4. Add をクリックして、環境変数の追加を確認する;
5. OPENAI_API_KEY を必ず追加してください;
6. Deploy をクリックして作成し、デプロイが完了するまで約 5 分間辛抱強く待つ。
## カスタムドメイン名の追加方法
\[TODO]
## 環境変数の変更方法
![vercel-env-edit](./images/vercel/vercel-env-edit.jpg)
1. 内部 Vercel プロジェクトコンソールに移動し、上部の設定ボタンをクリックします;
2. 左側の Environment Variables をクリックします;
3. 既存のエントリーの右側のボタンをクリックします;
4. 編集を選択して編集し、保存する。
⚠️️ 注意: [プロジェクトの再デプロイ](#再実装の方法)環境変数を変更するたびに、変更を有効にするために必要です!
## 再実装の方法
![vercel-redeploy](./images/vercel/vercel-redeploy.jpg)
1. Vercelプロジェクトの内部コンソールに移動し、一番上のDeploymentsボタンをクリックします;
2. リストの一番上の項目の右のボタンを選択します;
3. 再デプロイをクリックして再デプロイします。

View File

@ -1,39 +0,0 @@
# Vercel 사용 방법
## 새 프로젝트 생성 방법
이 프로젝트를 Github에서 포크한 후, 다시 배포하려면 Vercel에서 새로운 Vercel 프로젝트를 생성해야 하며, 다음 단계를 따라야 합니다.
![vercel-create-1](./images/vercel/vercel-create-1.jpg)
1. Vercel 콘솔 홈 페이지로 이동합니다;
2. 새로 추가를 클릭합니다;
3. 프로젝트를 선택합니다.
![vercel-create-2](./images/vercel/vercel-create-2.jpg)
1. Git 리포지토리 가져오기에서 chatgpt-next-web을 검색합니다. 2. 새 포크를 선택합니다;
2. 새로 포크된 프로젝트를 선택하고 가져오기를 클릭합니다.
![vercel-create-3](./images/vercel/vercel-create-3.jpg)
1. 프로젝트 구성 페이지에서 환경 변수 설정을 클릭하여 환경 변수 설정을 시작합니다;
2. OPENAI_API_KEY, CODE ([Access Code](https://github.com/Yidadaa/ChatGPT-Next-Web/blob/357296986609c14de10bf210871d30e2f67a8784/docs/faq-cn.md#%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F-code-%E6%98%AF%E4%BB%80%E4%B9%88%E5%BF%85%E9%A1%BB%E8%AE%BE%E7%BD%AE%E5%90%97)). 환경 변수를 설정합니다;
3. 환경 변수의 값을 입력합니다;
4. 추가를 클릭하여 환경 변수 추가를 확인합니다;
5. OPENAI_API_KEY를 추가해야 하며, 그렇지 않으면 작동하지 않습니다;
6. 배포를 클릭하여 도메인 이름 생성을 완료하고 배포가 완료될 때까지 약 5분간 기다립니다.
## 사용자 정의 도메인 네임 추가 방법
[TODO]
## 환경 변수 변경 방법
![vercel-env-edit](./images/vercel/vercel-env-edit.jpg)
1. 버셀 프로젝트의 내부 콘솔로 이동하여 상단의 설정 버튼을 클릭합니다;
2. 왼쪽의 환경 변수를 클릭합니다;
3. 기존 항목 오른쪽에 있는 버튼을 클릭합니다;
4. 편집을 선택하여 수정하고 저장합니다.
⚠️️ 참고: 환경 변수를 변경할 때마다 [프로젝트를 재배포](#如何重新部署)해야 변경 사항을 적용할 수 있습니다!
## 재배포 방법
![vercel-redeploy](./images/vercel/vercel-redeploy.jpg)
1. 버셀 내부 프로젝트 콘솔로 이동하여 상단의 배포 버튼을 클릭합니다;
2. 목록에서 맨 위 항목 오른쪽에 있는 버튼을 선택합니다;
3. 재배포를 클릭하여 재배포합니다.

View File

@ -64,8 +64,17 @@ if (mode !== "export") {
nextConfig.rewrites = async () => {
const ret = [
// adjust for previous version directly using "/api/proxy/" as proxy base route
{
source: "/api/proxy/:path*",
source: "/api/proxy/v1/:path*",
destination: "https://api.openai.com/v1/:path*",
},
{
source: "/api/proxy/google/:path*",
destination: "https://generativelanguage.googleapis.com/:path*",
},
{
source: "/api/proxy/openai/:path*",
destination: "https://api.openai.com/:path*",
},
{

10506
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
{
"name": "chatgpt-next-web",
"name": "nextchat",
"private": false,
"license": "mit",
"scripts": {
@ -25,6 +25,7 @@
"emoji-picker-react": "^4.5.15",
"fuse.js": "^7.0.0",
"html-to-image": "^1.11.11",
"katex": "^0.16.9",
"mermaid": "^10.6.1",
"nanoid": "^5.0.3",
"next": "^13.4.9",

View File

@ -1,4 +1,3 @@
User-agent: *
Disallow: /
User-agent: vitals.vercel-insights.com
Allow: /

View File

@ -1,4 +1,4 @@
const CHATGPT_NEXT_WEB_CACHE = "chatgpt-next-web-cache";
const CHATGPT_NEXT_WEB_CACHE = "chatgpt-gtering-web-cache";
self.addEventListener("activate", function (event) {
console.log("ServiceWorker activated.");

View File

@ -1,6 +1,6 @@
{
"name": "NextChat",
"short_name": "NextChat",
"name": "GterIng",
"short_name": "GterIng",
"icons": [
{
"src": "/android-chrome-192x192.png",

View File

@ -54,7 +54,7 @@ if ! command -v node >/dev/null || ! command -v git >/dev/null || ! command -v y
fi
# Clone the repository and install dependencies
git clone https://github.com/Yidadaa/ChatGPT-Next-Web
git clone https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web
cd ChatGPT-Next-Web
yarn install

643
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,23 +1,41 @@
[package]
name = "chatgpt-next-web"
name = "nextchat"
version = "0.1.0"
description = "A cross platform app for LLM ChatBot."
authors = ["Yidadaa"]
license = "mit"
repository = ""
default-run = "chatgpt-next-web"
default-run = "nextchat"
edition = "2021"
rust-version = "1.60"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "1.3.0", features = [] }
tauri-build = { version = "1.5.1", features = [] }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.3.0", features = ["notification-all", "fs-all", "clipboard-all", "dialog-all", "shell-open", "updater", "window-close", "window-hide", "window-maximize", "window-minimize", "window-set-icon", "window-set-ignore-cursor-events", "window-set-resizable", "window-show", "window-start-dragging", "window-unmaximize", "window-unminimize"] }
tauri = { version = "1.5.4", features = [
"notification-all",
"fs-all",
"clipboard-all",
"dialog-all",
"shell-open",
"updater",
"window-close",
"window-hide",
"window-maximize",
"window-minimize",
"window-set-icon",
"window-set-ignore-cursor-events",
"window-set-resizable",
"window-show",
"window-start-dragging",
"window-unmaximize",
"window-unminimize",
] }
tauri-plugin-window-state = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
[features]

View File

@ -9,7 +9,7 @@
},
"package": {
"productName": "NextChat",
"version": "2.10.2"
"version": "2.10.3"
},
"tauri": {
"allowlist": {
@ -86,12 +86,13 @@
}
},
"security": {
"csp": null
"csp": null,
"dangerousUseHttpScheme": true
},
"updater": {
"active": true,
"endpoints": [
"https://github.com/Yidadaa/ChatGPT-Next-Web/releases/latest/download/latest.json"
"https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/releases/latest/download/latest.json"
],
"dialog": false,
"windows": {

2028
yarn.lock

File diff suppressed because it is too large Load Diff