作者 202304001

项目部署

要显示太多修改。

为保证性能只显示 50 of 50+ 个文件。

  1 +{
  2 + "presets": [
  3 + [
  4 + "next/babel",
  5 + {
  6 + "preset-env": {
  7 + "targets": {
  8 + "browsers": ["> 0.25%, not dead"]
  9 + }
  10 + }
  11 + }
  12 + ]
  13 + ]
  14 +}
  1 +# Logs
  2 +logs
  3 +*.log
  4 +npm-debug.log*
  5 +yarn-debug.log*
  6 +yarn-error.log*
  7 +
  8 +# Runtime data
  9 +pids
  10 +*.pid
  11 +*.seed
  12 +*.pid.lock
  13 +
  14 +# Directory for instrumented libs generated by jscoverage/JSCover
  15 +lib-cov
  16 +
  17 +# Coverage directory used by tools like istanbul
  18 +coverage
  19 +*.lcov
  20 +
  21 +# nyc test coverage
  22 +.nyc_output
  23 +
  24 +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
  25 +.grunt
  26 +
  27 +# Node.js dependencies
  28 +/node_modules
  29 +/jspm_packages
  30 +
  31 +# TypeScript v1 declaration files
  32 +typings
  33 +
  34 +# Optional npm cache directory
  35 +.npm
  36 +
  37 +# Optional eslint cache
  38 +.eslintcache
  39 +
  40 +# Optional REPL history
  41 +.node_repl_history
  42 +
  43 +# Output of 'npm pack'
  44 +*.tgz
  45 +
  46 +# Yarn Integrity file
  47 +.yarn-integrity
  48 +
  49 +# dotenv environment variable files
  50 +.env
  51 +.env.test
  52 +
  53 +# local env files
  54 +.env*.local
  55 +
  56 +# Next.js build output
  57 +.next
  58 +out
  59 +
  60 +# Nuxt.js build output
  61 +.nuxt
  62 +dist
  63 +
  64 +# Gatsby files
  65 +.cache/
  66 +
  67 +
  68 +# Vuepress build output
  69 +.vuepress/dist
  70 +
  71 +# Serverless directories
  72 +.serverless/
  73 +
  74 +# FuseBox cache
  75 +.fusebox/
  76 +
  77 +# DynamoDB Local files
  78 +.dynamodb/
  79 +
  80 +# Temporary folders
  81 +tmp
  82 +temp
  83 +
  84 +# IDE and editor directories
  85 +.idea
  86 +.vscode
  87 +*.swp
  88 +*.swo
  89 +*~
  90 +
  91 +# OS generated files
  92 +.DS_Store
  93 +Thumbs.db
  94 +
  95 +# secret key
  96 +*.key
  97 +*.key.pub
  1 +public/serviceWorker.js
  2 +app/mcp/mcp_config.json
  3 +app/mcp/mcp_config.default.json
  1 +{
  2 + "extends": "next/core-web-vitals",
  3 + "plugins": ["prettier", "unused-imports"],
  4 + "rules": {
  5 + "unused-imports/no-unused-imports": "warn"
  6 + }
  7 +}
  1 +name: '🐛 Bug Report'
  2 +description: 'Report an bug'
  3 +title: '[Bug] '
  4 +labels: ['bug']
  5 +body:
  6 + - type: dropdown
  7 + attributes:
  8 + label: '📦 Deployment Method'
  9 + multiple: true
  10 + options:
  11 + - 'Official installation package'
  12 + - 'Vercel'
  13 + - 'Zeabur'
  14 + - 'Sealos'
  15 + - 'Netlify'
  16 + - 'Docker'
  17 + - 'Other'
  18 + validations:
  19 + required: true
  20 + - type: input
  21 + attributes:
  22 + label: '📌 Version'
  23 + validations:
  24 + required: true
  25 +
  26 + - type: dropdown
  27 + attributes:
  28 + label: '💻 Operating System'
  29 + multiple: true
  30 + options:
  31 + - 'Windows'
  32 + - 'macOS'
  33 + - 'Ubuntu'
  34 + - 'Other Linux'
  35 + - 'iOS'
  36 + - 'iPad OS'
  37 + - 'Android'
  38 + - 'Other'
  39 + validations:
  40 + required: true
  41 + - type: input
  42 + attributes:
  43 + label: '📌 System Version'
  44 + validations:
  45 + required: true
  46 + - type: dropdown
  47 + attributes:
  48 + label: '🌐 Browser'
  49 + multiple: true
  50 + options:
  51 + - 'Chrome'
  52 + - 'Edge'
  53 + - 'Safari'
  54 + - 'Firefox'
  55 + - 'Other'
  56 + validations:
  57 + required: true
  58 + - type: input
  59 + attributes:
  60 + label: '📌 Browser Version'
  61 + validations:
  62 + required: true
  63 + - type: textarea
  64 + attributes:
  65 + label: '🐛 Bug Description'
  66 + description: A clear and concise description of the bug, if the above option is `Other`, please also explain in detail.
  67 + validations:
  68 + required: true
  69 + - type: textarea
  70 + attributes:
  71 + label: '📷 Recurrence Steps'
  72 + description: A clear and concise description of how to recurrence.
  73 + - type: textarea
  74 + attributes:
  75 + label: '🚦 Expected Behavior'
  76 + description: A clear and concise description of what you expected to happen.
  77 + - type: textarea
  78 + attributes:
  79 + label: '📝 Additional Information'
  80 + description: If your problem needs further explanation, or if the issue you're seeing cannot be reproduced in a gist, please add more information here.
  1 +name: '🐛 反馈缺陷'
  2 +description: '反馈一个问题/缺陷'
  3 +title: '[Bug] '
  4 +labels: ['bug']
  5 +body:
  6 + - type: dropdown
  7 + attributes:
  8 + label: '📦 部署方式'
  9 + multiple: true
  10 + options:
  11 + - '官方安装包'
  12 + - 'Vercel'
  13 + - 'Zeabur'
  14 + - 'Sealos'
  15 + - 'Netlify'
  16 + - 'Docker'
  17 + - 'Other'
  18 + validations:
  19 + required: true
  20 + - type: input
  21 + attributes:
  22 + label: '📌 软件版本'
  23 + validations:
  24 + required: true
  25 +
  26 + - type: dropdown
  27 + attributes:
  28 + label: '💻 系统环境'
  29 + multiple: true
  30 + options:
  31 + - 'Windows'
  32 + - 'macOS'
  33 + - 'Ubuntu'
  34 + - 'Other Linux'
  35 + - 'iOS'
  36 + - 'iPad OS'
  37 + - 'Android'
  38 + - 'Other'
  39 + validations:
  40 + required: true
  41 + - type: input
  42 + attributes:
  43 + label: '📌 系统版本'
  44 + validations:
  45 + required: true
  46 + - type: dropdown
  47 + attributes:
  48 + label: '🌐 浏览器'
  49 + multiple: true
  50 + options:
  51 + - 'Chrome'
  52 + - 'Edge'
  53 + - 'Safari'
  54 + - 'Firefox'
  55 + - 'Other'
  56 + validations:
  57 + required: true
  58 + - type: input
  59 + attributes:
  60 + label: '📌 浏览器版本'
  61 + validations:
  62 + required: true
  63 + - type: textarea
  64 + attributes:
  65 + label: '🐛 问题描述'
  66 + description: 请提供一个清晰且简洁的问题描述,若上述选项为`Other`,也请详细说明。
  67 + validations:
  68 + required: true
  69 + - type: textarea
  70 + attributes:
  71 + label: '📷 复现步骤'
  72 + description: 请提供一个清晰且简洁的描述,说明如何复现问题。
  73 + - type: textarea
  74 + attributes:
  75 + label: '🚦 期望结果'
  76 + description: 请提供一个清晰且简洁的描述,说明您期望发生什么。
  77 + - type: textarea
  78 + attributes:
  79 + label: '📝 补充信息'
  80 + description: 如果您的问题需要进一步说明,或者您遇到的问题无法在一个简单的示例中复现,请在这里添加更多信息。
  1 +name: '🌠 Feature Request'
  2 +description: 'Suggest an idea'
  3 +title: '[Feature Request] '
  4 +labels: ['enhancement']
  5 +body:
  6 + - type: textarea
  7 + attributes:
  8 + label: '🥰 Feature Description'
  9 + description: Please add a clear and concise description of the problem you are seeking to solve with this feature request.
  10 + validations:
  11 + required: true
  12 + - type: textarea
  13 + attributes:
  14 + label: '🧐 Proposed Solution'
  15 + description: Describe the solution you'd like in a clear and concise manner.
  16 + validations:
  17 + required: true
  18 + - type: textarea
  19 + attributes:
  20 + label: '📝 Additional Information'
  21 + description: Add any other context about the problem here.
  1 +name: '🌠 功能需求'
  2 +description: '提出需求或建议'
  3 +title: '[Feature Request] '
  4 +labels: ['enhancement']
  5 +body:
  6 + - type: textarea
  7 + attributes:
  8 + label: '🥰 需求描述'
  9 + description: 请添加一个清晰且简洁的问题描述,阐述您希望通过这个功能需求解决的问题。
  10 + validations:
  11 + required: true
  12 + - type: textarea
  13 + attributes:
  14 + label: '🧐 解决方案'
  15 + description: 请清晰且简洁地描述您想要的解决方案。
  16 + validations:
  17 + required: true
  18 + - type: textarea
  19 + attributes:
  20 + label: '📝 补充信息'
  21 + description: 在这里添加关于问题的任何其他背景信息。
  1 +#### 💻 变更类型 | Change Type
  2 +
  3 +<!-- For change type, change [ ] to [x]. -->
  4 +
  5 +- [ ] feat <!-- 引入新功能 | Introduce new features -->
  6 +- [ ] fix <!-- 修复 Bug | Fix a bug -->
  7 +- [ ] refactor <!-- 重构代码(既不修复 Bug 也不添加新功能) | Refactor code that neither fixes a bug nor adds a feature -->
  8 +- [ ] perf <!-- 提升性能的代码变更 | A code change that improves performance -->
  9 +- [ ] style <!-- 添加或更新不影响代码含义的样式文件 | Add or update style files that do not affect the meaning of the code -->
  10 +- [ ] test <!-- 添加缺失的测试或纠正现有的测试 | Adding missing tests or correcting existing tests -->
  11 +- [ ] docs <!-- 仅文档更新 | Documentation only changes -->
  12 +- [ ] ci <!-- 修改持续集成配置文件和脚本 | Changes to our CI configuration files and scripts -->
  13 +- [ ] chore <!-- 其他不修改 src 或 test 文件的变更 | Other changes that don’t modify src or test files -->
  14 +- [ ] build <!-- 进行架构变更 | Make architectural changes -->
  15 +
  16 +#### 🔀 变更说明 | Description of Change
  17 +
  18 +<!--
  19 +感谢您的 Pull Request ,请提供此 Pull Request 的变更说明
  20 +Thank you for your Pull Request. Please provide a description above.
  21 +-->
  22 +
  23 +#### 📝 补充信息 | Additional Information
  24 +
  25 +<!--
  26 +请添加与此 Pull Request 相关的补充信息
  27 +Add any other context about the Pull Request here.
  28 +-->
  1 +# To get started with Dependabot version updates, you'll need to specify which
  2 +# package ecosystems to update and where the package manifests are located.
  3 +# Please see the documentation for all configuration options:
  4 +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
  5 +
  6 +version: 2
  7 +updates:
  8 + - package-ecosystem: "npm" # See documentation for possible values
  9 + directory: "/" # Location of package manifests
  10 + schedule:
  11 + interval: "weekly"
  1 +name: Release App
  2 +
  3 +on:
  4 + workflow_dispatch:
  5 + release:
  6 + types: [published]
  7 +
  8 +jobs:
  9 + create-release:
  10 + permissions:
  11 + contents: write
  12 + runs-on: ubuntu-latest
  13 + outputs:
  14 + release_id: ${{ steps.create-release.outputs.result }}
  15 +
  16 + steps:
  17 + - uses: actions/checkout@v3
  18 + - name: setup node
  19 + uses: actions/setup-node@v3
  20 + with:
  21 + node-version: 18
  22 + - name: get version
  23 + run: echo "PACKAGE_VERSION=$(node -p "require('./src-tauri/tauri.conf.json').package.version")" >> $GITHUB_ENV
  24 + - name: create release
  25 + id: create-release
  26 + uses: actions/github-script@v6
  27 + with:
  28 + script: |
  29 + const { data } = await github.rest.repos.getLatestRelease({
  30 + owner: context.repo.owner,
  31 + repo: context.repo.repo,
  32 + })
  33 + return data.id
  34 +
  35 + build-tauri:
  36 + needs: create-release
  37 + permissions:
  38 + contents: write
  39 + strategy:
  40 + fail-fast: false
  41 + matrix:
  42 + config:
  43 + - os: ubuntu-latest
  44 + arch: x86_64
  45 + rust_target: x86_64-unknown-linux-gnu
  46 + - os: macos-latest
  47 + arch: aarch64
  48 + rust_target: x86_64-apple-darwin,aarch64-apple-darwin
  49 + - os: windows-latest
  50 + arch: x86_64
  51 + rust_target: x86_64-pc-windows-msvc
  52 +
  53 + runs-on: ${{ matrix.config.os }}
  54 + steps:
  55 + - uses: actions/checkout@v3
  56 + - name: setup node
  57 + uses: actions/setup-node@v3
  58 + with:
  59 + node-version: 18
  60 + cache: 'yarn'
  61 + - name: install Rust stable
  62 + uses: dtolnay/rust-toolchain@stable
  63 + with:
  64 + targets: ${{ matrix.config.rust_target }}
  65 + - uses: Swatinem/rust-cache@v2
  66 + with:
  67 + key: ${{ matrix.config.os }}
  68 + - name: install dependencies (ubuntu only)
  69 + if: matrix.config.os == 'ubuntu-latest'
  70 + run: |
  71 + sudo apt-get update
  72 + sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf
  73 + - name: install frontend dependencies
  74 + run: yarn install # change this to npm or pnpm depending on which one you use
  75 + - uses: tauri-apps/tauri-action@v0
  76 + env:
  77 + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  78 + TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
  79 + TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
  80 + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
  81 + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
  82 + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
  83 + APPLE_ID: ${{ secrets.APPLE_ID }}
  84 + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
  85 + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
  86 + with:
  87 + releaseId: ${{ needs.create-release.outputs.release_id }}
  88 + args: ${{ matrix.config.os == 'macos-latest' && '--target universal-apple-darwin' || '' }}
  89 +
  90 + publish-release:
  91 + permissions:
  92 + contents: write
  93 + runs-on: ubuntu-latest
  94 + needs: [create-release, build-tauri]
  95 +
  96 + steps:
  97 + - name: publish release
  98 + id: publish-release
  99 + uses: actions/github-script@v6
  100 + env:
  101 + release_id: ${{ needs.create-release.outputs.release_id }}
  102 + with:
  103 + script: |
  104 + github.rest.repos.updateRelease({
  105 + owner: context.repo.owner,
  106 + repo: context.repo.repo,
  107 + release_id: process.env.release_id,
  108 + draft: false,
  109 + prerelease: false
  110 + })
  1 +name: VercelPreviewDeployment
  2 +
  3 +on:
  4 + pull_request_target:
  5 + types:
  6 + - review_requested
  7 +
  8 +env:
  9 + VERCEL_TEAM: ${{ secrets.VERCEL_TEAM }}
  10 + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
  11 + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
  12 + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
  13 + VERCEL_PR_DOMAIN_SUFFIX: ${{ secrets.VERCEL_PR_DOMAIN_SUFFIX }}
  14 +
  15 +permissions:
  16 + contents: read
  17 + statuses: write
  18 + pull-requests: write
  19 +
  20 +jobs:
  21 + deploy-preview:
  22 + runs-on: ubuntu-latest
  23 + steps:
  24 + - uses: actions/checkout@v2
  25 + with:
  26 + ref: ${{ github.event.pull_request.head.sha }}
  27 +
  28 + - name: Extract branch name
  29 + shell: bash
  30 + run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> "$GITHUB_OUTPUT"
  31 + id: extract_branch
  32 +
  33 + - name: Hash branch name
  34 + uses: pplanel/hash-calculator-action@v1.3.1
  35 + id: hash_branch
  36 + with:
  37 + input: ${{ steps.extract_branch.outputs.branch }}
  38 + method: MD5
  39 +
  40 + - name: Set Environment Variables
  41 + id: set_env
  42 + if: github.event_name == 'pull_request_target'
  43 + run: |
  44 + echo "VERCEL_ALIAS_DOMAIN=${{ github.event.pull_request.number }}-${{ github.workflow }}.${VERCEL_PR_DOMAIN_SUFFIX}" >> $GITHUB_OUTPUT
  45 +
  46 + - name: Install Vercel CLI
  47 + run: npm install --global vercel@latest
  48 +
  49 + - name: Cache dependencies
  50 + uses: actions/cache@v4
  51 + id: cache-npm
  52 + with:
  53 + path: ~/.npm
  54 + key: npm-${{ hashFiles('package-lock.json') }}
  55 + restore-keys: npm-
  56 +
  57 + - name: Pull Vercel Environment Information
  58 + run: vercel pull --yes --environment=preview --token=${VERCEL_TOKEN}
  59 +
  60 + - name: Deploy Project Artifacts to Vercel
  61 + id: vercel
  62 + env:
  63 + META_TAG: ${{ steps.hash_branch.outputs.digest }}-${{ github.run_number }}-${{ github.run_attempt}}
  64 + run: |
  65 + set -e
  66 + vercel pull --yes --environment=preview --token=${VERCEL_TOKEN}
  67 + vercel build --token=${VERCEL_TOKEN}
  68 + vercel deploy --prebuilt --archive=tgz --token=${VERCEL_TOKEN} --meta base_hash=${{ env.META_TAG }}
  69 +
  70 + DEFAULT_URL=$(vercel ls --token=${VERCEL_TOKEN} --meta base_hash=${{ env.META_TAG }})
  71 + ALIAS_URL=$(vercel alias set ${DEFAULT_URL} ${{ steps.set_env.outputs.VERCEL_ALIAS_DOMAIN }} --token=${VERCEL_TOKEN} --scope ${VERCEL_TEAM}| awk '{print $3}')
  72 +
  73 + echo "New preview URL: ${DEFAULT_URL}"
  74 + echo "New alias URL: ${ALIAS_URL}"
  75 + echo "VERCEL_URL=${ALIAS_URL}" >> "$GITHUB_OUTPUT"
  76 +
  77 + - uses: mshick/add-pr-comment@v2
  78 + with:
  79 + message: |
  80 + Your build has completed!
  81 +
  82 + [Preview deployment](${{ steps.vercel.outputs.VERCEL_URL }})
  1 +name: Publish Docker image
  2 +
  3 +on:
  4 + workflow_dispatch:
  5 + release:
  6 + types: [published]
  7 +
  8 +jobs:
  9 + push_to_registry:
  10 + name: Push Docker image to Docker Hub
  11 + runs-on: ubuntu-latest
  12 + steps:
  13 + -
  14 + name: Check out the repo
  15 + uses: actions/checkout@v3
  16 + -
  17 + name: Log in to Docker Hub
  18 + uses: docker/login-action@v2
  19 + with:
  20 + username: ${{ secrets.DOCKER_USERNAME }}
  21 + password: ${{ secrets.DOCKER_PASSWORD }}
  22 +
  23 + -
  24 + name: Extract metadata (tags, labels) for Docker
  25 + id: meta
  26 + uses: docker/metadata-action@v4
  27 + with:
  28 + images: yidadaa/chatgpt-next-web
  29 + tags: |
  30 + type=raw,value=latest
  31 + type=ref,event=tag
  32 +
  33 + -
  34 + name: Set up QEMU
  35 + uses: docker/setup-qemu-action@v2
  36 +
  37 + -
  38 + name: Set up Docker Buildx
  39 + uses: docker/setup-buildx-action@v2
  40 +
  41 + -
  42 + name: Build and push Docker image
  43 + uses: docker/build-push-action@v4
  44 + with:
  45 + context: .
  46 + platforms: linux/amd64,linux/arm64
  47 + push: true
  48 + tags: ${{ steps.meta.outputs.tags }}
  49 + labels: ${{ steps.meta.outputs.labels }}
  50 + cache-from: type=gha
  51 + cache-to: type=gha,mode=max
  52 +
  1 +name: Issue Translator
  2 +on:
  3 + issue_comment:
  4 + types: [created]
  5 + issues:
  6 + types: [opened]
  7 +
  8 +jobs:
  9 + build:
  10 + runs-on: ubuntu-latest
  11 + steps:
  12 + - uses: usthe/issues-translate-action@v2.7
  13 + with:
  14 + IS_MODIFY_TITLE: false
  15 + CUSTOM_BOT_NOTE: Bot detected the issue body's language is not English, translate it automatically.
  1 +name: Removedeploypreview
  2 +
  3 +permissions:
  4 + contents: read
  5 + statuses: write
  6 + pull-requests: write
  7 +
  8 +env:
  9 + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
  10 + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
  11 + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
  12 +
  13 +on:
  14 + pull_request_target:
  15 + types:
  16 + - closed
  17 +
  18 +jobs:
  19 + delete-deployments:
  20 + runs-on: ubuntu-latest
  21 + steps:
  22 + - uses: actions/checkout@v2
  23 +
  24 + - name: Extract branch name
  25 + shell: bash
  26 + run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> $GITHUB_OUTPUT
  27 + id: extract_branch
  28 +
  29 + - name: Hash branch name
  30 + uses: pplanel/hash-calculator-action@v1.3.1
  31 + id: hash_branch
  32 + with:
  33 + input: ${{ steps.extract_branch.outputs.branch }}
  34 + method: MD5
  35 +
  36 + - name: Call the delete-deployment-preview.sh script
  37 + env:
  38 + META_TAG: ${{ steps.hash_branch.outputs.digest }}
  39 + run: |
  40 + bash ./scripts/delete-deployment-preview.sh
  1 +name: Upstream Sync
  2 +
  3 +permissions:
  4 + contents: write
  5 +
  6 +on:
  7 + schedule:
  8 + - cron: "0 0 * * *" # every day
  9 + workflow_dispatch:
  10 +
  11 +jobs:
  12 + sync_latest_from_upstream:
  13 + name: Sync latest commits from upstream repo
  14 + runs-on: ubuntu-latest
  15 + if: ${{ github.event.repository.fork }}
  16 +
  17 + steps:
  18 + # Step 1: run a standard checkout action
  19 + - name: Checkout target repo
  20 + uses: actions/checkout@v3
  21 +
  22 + # Step 2: run the sync action
  23 + - name: Sync upstream changes
  24 + id: sync
  25 + uses: aormsby/Fork-Sync-With-Upstream-action@v3.4
  26 + with:
  27 + upstream_sync_repo: ChatGPTNextWeb/ChatGPT-Next-Web
  28 + upstream_sync_branch: main
  29 + target_sync_branch: main
  30 + target_repo_token: ${{ secrets.GITHUB_TOKEN }} # automatically generated, no need to set
  31 +
  32 + # Set test_mode true to run tests instead of the true action!!
  33 + test_mode: false
  34 +
  35 + - name: Sync check
  36 + if: failure()
  37 + run: |
  38 + 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"
  39 + 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"
  40 + exit 1
  1 +name: Run Tests
  2 +
  3 +on:
  4 + push:
  5 + branches:
  6 + - main
  7 + tags:
  8 + - "!*"
  9 + pull_request:
  10 + types:
  11 + - review_requested
  12 +
  13 +jobs:
  14 + test:
  15 + runs-on: ubuntu-latest
  16 +
  17 + steps:
  18 + - name: Checkout repository
  19 + uses: actions/checkout@v4
  20 +
  21 + - name: Set up Node.js
  22 + uses: actions/setup-node@v3
  23 + with:
  24 + node-version: 18
  25 + cache: "yarn"
  26 +
  27 + - name: Cache node_modules
  28 + uses: actions/cache@v4
  29 + with:
  30 + path: node_modules
  31 + key: ${{ runner.os }}-node_modules-${{ hashFiles('**/yarn.lock') }}
  32 + restore-keys: |
  33 + ${{ runner.os }}-node_modules-
  34 +
  35 + - name: Install dependencies
  36 + run: yarn install
  37 +
  38 + - name: Run Jest tests
  39 + run: yarn test:ci
  1 +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
  2 +
  3 +# dependencies
  4 +/node_modules
  5 +/.pnp
  6 +.pnp.js
  7 +
  8 +# testing
  9 +/coverage
  10 +
  11 +# next.js
  12 +/.next/
  13 +/out/
  14 +
  15 +# production
  16 +/build
  17 +
  18 +# misc
  19 +.DS_Store
  20 +*.pem
  21 +
  22 +# debug
  23 +npm-debug.log*
  24 +yarn-debug.log*
  25 +yarn-error.log*
  26 +.pnpm-debug.log*
  27 +
  28 +# local env files
  29 +.env*.local
  30 +
  31 +# vercel
  32 +.vercel
  33 +
  34 +# typescript
  35 +*.tsbuildinfo
  36 +next-env.d.ts
  37 +dev
  38 +
  39 +.vscode
  40 +.idea
  41 +
  42 +# docker-compose env files
  43 +.env
  44 +
  45 +*.key
  46 +*.key.pub
  47 +
  48 +masks.json
  49 +
  50 +# mcp config
  51 +app/mcp/mcp_config.json
  1 +# This configuration file was automatically generated by Gitpod.
  2 +# Please adjust to your needs (see https://www.gitpod.io/docs/introduction/learn-gitpod/gitpod-yaml)
  3 +# and commit this file to your remote git repository to share the goodness with others.
  4 +
  5 +# Learn more from ready-to-use templates: https://www.gitpod.io/docs/introduction/getting-started/quickstart
  6 +
  7 +tasks:
  8 + - init: yarn install && yarn run dev
  9 + command: yarn run dev
  10 +
  11 +
  1 +#!/usr/bin/env sh
  2 +. "$(dirname -- "$0")/_/husky.sh"
  3 +
  4 +npx lint-staged
  1 +{
  2 + "./app/**/*.{js,ts,jsx,tsx,json,html,css,md}": [
  3 + "eslint --fix",
  4 + "prettier --write"
  5 + ]
  6 +}
  1 +module.exports = {
  2 + printWidth: 80,
  3 + tabWidth: 2,
  4 + useTabs: false,
  5 + semi: true,
  6 + singleQuote: false,
  7 + trailingComma: 'all',
  8 + bracketSpacing: true,
  9 + arrowParens: 'always',
  10 +};
  1 +# Contributor Covenant Code of Conduct
  2 +
  3 +## Our Pledge
  4 +
  5 +We as members, contributors, and leaders pledge to make participation in our
  6 +community a harassment-free experience for everyone, regardless of age, body
  7 +size, visible or invisible disability, ethnicity, sex characteristics, gender
  8 +identity and expression, level of experience, education, socio-economic status,
  9 +nationality, personal appearance, race, religion, or sexual identity
  10 +and orientation.
  11 +
  12 +We pledge to act and interact in ways that contribute to an open, welcoming,
  13 +diverse, inclusive, and healthy community.
  14 +
  15 +## Our Standards
  16 +
  17 +Examples of behavior that contributes to a positive environment for our
  18 +community include:
  19 +
  20 +* Demonstrating empathy and kindness toward other people
  21 +* Being respectful of differing opinions, viewpoints, and experiences
  22 +* Giving and gracefully accepting constructive feedback
  23 +* Accepting responsibility and apologizing to those affected by our mistakes,
  24 + and learning from the experience
  25 +* Focusing on what is best not just for us as individuals, but for the
  26 + overall community
  27 +
  28 +Examples of unacceptable behavior include:
  29 +
  30 +* The use of sexualized language or imagery, and sexual attention or
  31 + advances of any kind
  32 +* Trolling, insulting or derogatory comments, and personal or political attacks
  33 +* Public or private harassment
  34 +* Publishing others' private information, such as a physical or email
  35 + address, without their explicit permission
  36 +* Other conduct which could reasonably be considered inappropriate in a
  37 + professional setting
  38 +
  39 +## Enforcement Responsibilities
  40 +
  41 +Community leaders are responsible for clarifying and enforcing our standards of
  42 +acceptable behavior and will take appropriate and fair corrective action in
  43 +response to any behavior that they deem inappropriate, threatening, offensive,
  44 +or harmful.
  45 +
  46 +Community leaders have the right and responsibility to remove, edit, or reject
  47 +comments, commits, code, wiki edits, issues, and other contributions that are
  48 +not aligned to this Code of Conduct, and will communicate reasons for moderation
  49 +decisions when appropriate.
  50 +
  51 +## Scope
  52 +
  53 +This Code of Conduct applies within all community spaces, and also applies when
  54 +an individual is officially representing the community in public spaces.
  55 +Examples of representing our community include using an official e-mail address,
  56 +posting via an official social media account, or acting as an appointed
  57 +representative at an online or offline event.
  58 +
  59 +## Enforcement
  60 +
  61 +Instances of abusive, harassing, or otherwise unacceptable behavior may be
  62 +reported to the community leaders responsible for enforcement at
  63 +flynn.zhang@foxmail.com.
  64 +All complaints will be reviewed and investigated promptly and fairly.
  65 +
  66 +All community leaders are obligated to respect the privacy and security of the
  67 +reporter of any incident.
  68 +
  69 +## Enforcement Guidelines
  70 +
  71 +Community leaders will follow these Community Impact Guidelines in determining
  72 +the consequences for any action they deem in violation of this Code of Conduct:
  73 +
  74 +### 1. Correction
  75 +
  76 +**Community Impact**: Use of inappropriate language or other behavior deemed
  77 +unprofessional or unwelcome in the community.
  78 +
  79 +**Consequence**: A private, written warning from community leaders, providing
  80 +clarity around the nature of the violation and an explanation of why the
  81 +behavior was inappropriate. A public apology may be requested.
  82 +
  83 +### 2. Warning
  84 +
  85 +**Community Impact**: A violation through a single incident or series
  86 +of actions.
  87 +
  88 +**Consequence**: A warning with consequences for continued behavior. No
  89 +interaction with the people involved, including unsolicited interaction with
  90 +those enforcing the Code of Conduct, for a specified period of time. This
  91 +includes avoiding interactions in community spaces as well as external channels
  92 +like social media. Violating these terms may lead to a temporary or
  93 +permanent ban.
  94 +
  95 +### 3. Temporary Ban
  96 +
  97 +**Community Impact**: A serious violation of community standards, including
  98 +sustained inappropriate behavior.
  99 +
  100 +**Consequence**: A temporary ban from any sort of interaction or public
  101 +communication with the community for a specified period of time. No public or
  102 +private interaction with the people involved, including unsolicited interaction
  103 +with those enforcing the Code of Conduct, is allowed during this period.
  104 +Violating these terms may lead to a permanent ban.
  105 +
  106 +### 4. Permanent Ban
  107 +
  108 +**Community Impact**: Demonstrating a pattern of violation of community
  109 +standards, including sustained inappropriate behavior, harassment of an
  110 +individual, or aggression toward or disparagement of classes of individuals.
  111 +
  112 +**Consequence**: A permanent ban from any sort of public interaction within
  113 +the community.
  114 +
  115 +## Attribution
  116 +
  117 +This Code of Conduct is adapted from the [Contributor Covenant][homepage],
  118 +version 2.0, available at
  119 +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
  120 +
  121 +Community Impact Guidelines were inspired by [Mozilla's code of conduct
  122 +enforcement ladder](https://github.com/mozilla/diversity).
  123 +
  124 +[homepage]: https://www.contributor-covenant.org
  125 +
  126 +For answers to common questions about this code of conduct, see the FAQ at
  127 +https://www.contributor-covenant.org/faq. Translations are available at
  128 +https://www.contributor-covenant.org/translations.
  1 +FROM node:18-alpine AS base
  2 +
  3 +FROM base AS deps
  4 +
  5 +RUN apk add --no-cache libc6-compat
  6 +
  7 +WORKDIR /app
  8 +
  9 +COPY package.json yarn.lock ./
  10 +
  11 +RUN yarn config set registry 'https://registry.npmmirror.com/'
  12 +RUN yarn install
  13 +
  14 +FROM base AS builder
  15 +
  16 +RUN apk update && apk add --no-cache git
  17 +
  18 +ENV OPENAI_API_KEY=""
  19 +ENV GOOGLE_API_KEY=""
  20 +ENV CODE=""
  21 +
  22 +WORKDIR /app
  23 +COPY --from=deps /app/node_modules ./node_modules
  24 +COPY . .
  25 +
  26 +RUN yarn build
  27 +
  28 +FROM base AS runner
  29 +WORKDIR /app
  30 +
  31 +RUN apk add proxychains-ng
  32 +
  33 +ENV PROXY_URL=""
  34 +ENV OPENAI_API_KEY=""
  35 +ENV GOOGLE_API_KEY=""
  36 +ENV CODE=""
  37 +ENV ENABLE_MCP=""
  38 +
  39 +COPY --from=builder /app/public ./public
  40 +COPY --from=builder /app/.next/standalone ./
  41 +COPY --from=builder /app/.next/static ./.next/static
  42 +COPY --from=builder /app/.next/server ./.next/server
  43 +
  44 +RUN mkdir -p /app/app/mcp && chmod 777 /app/app/mcp
  45 +COPY --from=builder /app/app/mcp/mcp_config.default.json /app/app/mcp/mcp_config.json
  46 +
  47 +EXPOSE 3000
  48 +
  49 +CMD if [ -n "$PROXY_URL" ]; then \
  50 + export HOSTNAME="0.0.0.0"; \
  51 + protocol=$(echo $PROXY_URL | cut -d: -f1); \
  52 + host=$(echo $PROXY_URL | cut -d/ -f3 | cut -d: -f1); \
  53 + port=$(echo $PROXY_URL | cut -d: -f3); \
  54 + conf=/etc/proxychains.conf; \
  55 + echo "strict_chain" > $conf; \
  56 + echo "proxy_dns" >> $conf; \
  57 + echo "remote_dns_subnet 224" >> $conf; \
  58 + echo "tcp_read_time_out 15000" >> $conf; \
  59 + echo "tcp_connect_time_out 8000" >> $conf; \
  60 + echo "localnet 127.0.0.0/255.0.0.0" >> $conf; \
  61 + echo "localnet ::1/128" >> $conf; \
  62 + echo "[ProxyList]" >> $conf; \
  63 + echo "$protocol $host $port" >> $conf; \
  64 + cat /etc/proxychains.conf; \
  65 + proxychains -f $conf node server.js; \
  66 + else \
  67 + node server.js; \
  68 + fi
  1 +MIT License
  2 +
  3 +Copyright (c) 2023-2025 NextChat
  4 +
  5 +Permission is hereby granted, free of charge, to any person obtaining a copy
  6 +of this software and associated documentation files (the "Software"), to deal
  7 +in the Software without restriction, including without limitation the rights
  8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9 +copies of the Software, and to permit persons to whom the Software is
  10 +furnished to do so, subject to the following conditions:
  11 +
  12 +The above copyright notice and this permission notice shall be included in all
  13 +copies or substantial portions of the Software.
  14 +
  15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21 +SOFTWARE.
  1 +<div align="center">
  2 +
  3 +<a href='https://nextchat.club'>
  4 + <img src="https://github.com/user-attachments/assets/83bdcc07-ae5e-4954-a53a-ac151ba6ccf3" width="1000" alt="icon"/>
  5 +</a>
  6 +
  7 +
  8 +
  9 +
  10 +<h1 align="center">NextChat (ChatGPT Next Web)</h1>
  11 +
  12 +English / [简体中文](./README_CN.md)
  13 +
  14 +<a href="https://trendshift.io/repositories/5973" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5973" alt="ChatGPTNextWeb%2FChatGPT-Next-Web | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
  15 +
  16 +
  17 +✨ Light and Fast AI Assistant,with Claude, DeepSeek, GPT4 & Gemini Pro support.
  18 +
  19 +[![Saas][Saas-image]][saas-url]
  20 +[![Web][Web-image]][web-url]
  21 +[![Windows][Windows-image]][download-url]
  22 +[![MacOS][MacOS-image]][download-url]
  23 +[![Linux][Linux-image]][download-url]
  24 +
  25 +[NextChatAI](https://nextchat.club?utm_source=readme) / [Web App Demo](https://app.nextchat.dev) / [Desktop App](https://github.com/Yidadaa/ChatGPT-Next-Web/releases) / [Discord](https://discord.gg/YCkeafCafC) / [Enterprise Edition](#enterprise-edition) / [Twitter](https://twitter.com/NextChatDev)
  26 +
  27 +
  28 +[saas-url]: https://nextchat.club?utm_source=readme
  29 +[saas-image]: https://img.shields.io/badge/NextChat-Saas-green?logo=microsoftedge
  30 +[web-url]: https://app.nextchat.dev/
  31 +[download-url]: https://github.com/Yidadaa/ChatGPT-Next-Web/releases
  32 +[Web-image]: https://img.shields.io/badge/Web-PWA-orange?logo=microsoftedge
  33 +[Windows-image]: https://img.shields.io/badge/-Windows-blue?logo=windows
  34 +[MacOS-image]: https://img.shields.io/badge/-MacOS-black?logo=apple
  35 +[Linux-image]: https://img.shields.io/badge/-Linux-333?logo=ubuntu
  36 +
  37 +[<img src="https://zeabur.com/button.svg" alt="Deploy on Zeabur" height="30">](https://zeabur.com/templates/ZBUEFA) [<img src="https://vercel.com/button" alt="Deploy on Vercel" height="30">](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FChatGPTNextWeb%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=nextchat&repository-name=NextChat) [<img src="https://gitpod.io/button/open-in-gitpod.svg" alt="Open in Gitpod" height="30">](https://gitpod.io/#https://github.com/ChatGPTNextWeb/NextChat)
  38 +
  39 +[<img src="https://github.com/user-attachments/assets/903482d4-3e87-4134-9af1-f2588fa90659" height="50" width="" >](https://monica.im/?utm=nxcrp)
  40 +
  41 +</div>
  42 +
  43 +## 👋 Hey, NextChat is going to develop a native app!
  44 +
  45 +> This week we are going to start working on iOS and Android APP, and we want to find some reliable friends to do it together!
  46 +
  47 +
  48 +✨ Several key points:
  49 +
  50 +- Starting from 0, you are a veteran
  51 +- Completely open source, not hidden
  52 +- Native development, pursuing the ultimate experience
  53 +
  54 +Will you come and do something together? 😎
  55 +
  56 +https://github.com/ChatGPTNextWeb/NextChat/issues/6269
  57 +
  58 +#Seeking for talents is thirsty #lack of people
  59 +
  60 +
  61 +## 🥳 Cheer for DeepSeek, China's AI star!
  62 + > Purpose-Built UI for DeepSeek Reasoner Model
  63 +
  64 +<img src="https://github.com/user-attachments/assets/f3952210-3af1-4dc0-9b81-40eaa4847d9a"/>
  65 +
  66 +
  67 +
  68 +## 🫣 NextChat Support MCP !
  69 +> Before build, please set env ENABLE_MCP=true
  70 +
  71 +<img src="https://github.com/user-attachments/assets/d8851f40-4e36-4335-b1a4-ec1e11488c7e"/>
  72 +
  73 +
  74 +## Enterprise Edition
  75 +
  76 +Meeting Your Company's Privatization and Customization Deployment Requirements:
  77 +- **Brand Customization**: Tailored VI/UI to seamlessly align with your corporate brand image.
  78 +- **Resource Integration**: Unified configuration and management of dozens of AI resources by company administrators, ready for use by team members.
  79 +- **Permission Control**: Clearly defined member permissions, resource permissions, and knowledge base permissions, all controlled via a corporate-grade Admin Panel.
  80 +- **Knowledge Integration**: Combining your internal knowledge base with AI capabilities, making it more relevant to your company's specific business needs compared to general AI.
  81 +- **Security Auditing**: Automatically intercept sensitive inquiries and trace all historical conversation records, ensuring AI adherence to corporate information security standards.
  82 +- **Private Deployment**: Enterprise-level private deployment supporting various mainstream private cloud solutions, ensuring data security and privacy protection.
  83 +- **Continuous Updates**: Ongoing updates and upgrades in cutting-edge capabilities like multimodal AI, ensuring consistent innovation and advancement.
  84 +
  85 +For enterprise inquiries, please contact: **business@nextchat.dev**
  86 +
  87 +## Screenshots
  88 +
  89 +![Settings](./docs/images/settings.png)
  90 +
  91 +![More](./docs/images/more.png)
  92 +
  93 +
  94 +## Features
  95 +
  96 +- **Deploy for free with one-click** on Vercel in under 1 minute
  97 +- Compact client (~5MB) on Linux/Windows/MacOS, [download it now](https://github.com/Yidadaa/ChatGPT-Next-Web/releases)
  98 +- Fully compatible with self-deployed LLMs, recommended for use with [RWKV-Runner](https://github.com/josStorer/RWKV-Runner) or [LocalAI](https://github.com/go-skynet/LocalAI)
  99 +- Privacy first, all data is stored locally in the browser
  100 +- Markdown support: LaTex, mermaid, code highlight, etc.
  101 +- Responsive design, dark mode and PWA
  102 +- Fast first screen loading speed (~100kb), support streaming response
  103 +- New in v2: create, share and debug your chat tools with prompt templates (mask)
  104 +- Awesome prompts powered by [awesome-chatgpt-prompts-zh](https://github.com/PlexPt/awesome-chatgpt-prompts-zh) and [awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts)
  105 +- Automatically compresses chat history to support long conversations while also saving your tokens
  106 +- I18n: English, 简体中文, 繁体中文, 日本語, Français, Español, Italiano, Türkçe, Deutsch, Tiếng Việt, Русский, Čeština, 한국어, Indonesia
  107 +
  108 +<div align="center">
  109 +
  110 +![主界面](./docs/images/cover.png)
  111 +
  112 +</div>
  113 +
  114 +## Roadmap
  115 +
  116 +- [x] System Prompt: pin a user defined prompt as system prompt [#138](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/138)
  117 +- [x] User Prompt: user can edit and save custom prompts to prompt list
  118 +- [x] Prompt Template: create a new chat with pre-defined in-context prompts [#993](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/993)
  119 +- [x] Share as image, share to ShareGPT [#1741](https://github.com/Yidadaa/ChatGPT-Next-Web/pull/1741)
  120 +- [x] Desktop App with tauri
  121 +- [x] Self-host Model: Fully compatible with [RWKV-Runner](https://github.com/josStorer/RWKV-Runner), as well as server deployment of [LocalAI](https://github.com/go-skynet/LocalAI): llama/gpt4all/rwkv/vicuna/koala/gpt4all-j/cerebras/falcon/dolly etc.
  122 +- [x] Artifacts: Easily preview, copy and share generated content/webpages through a separate window [#5092](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/pull/5092)
  123 +- [x] Plugins: support network search, calculator, any other apis etc. [#165](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/165) [#5353](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/issues/5353)
  124 + - [x] network search, calculator, any other apis etc. [#165](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/165) [#5353](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/issues/5353)
  125 +- [x] Supports Realtime Chat [#5672](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/issues/5672)
  126 +- [ ] local knowledge base
  127 +
  128 +## What's New
  129 +- 🚀 v2.15.8 Now supports Realtime Chat [#5672](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/issues/5672)
  130 +- 🚀 v2.15.4 The Application supports using Tauri fetch LLM API, MORE SECURITY! [#5379](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/issues/5379)
  131 +- 🚀 v2.15.0 Now supports Plugins! Read this: [NextChat-Awesome-Plugins](https://github.com/ChatGPTNextWeb/NextChat-Awesome-Plugins)
  132 +- 🚀 v2.14.0 Now supports Artifacts & SD
  133 +- 🚀 v2.10.1 support Google Gemini Pro model.
  134 +- 🚀 v2.9.11 you can use azure endpoint now.
  135 +- 🚀 v2.8 now we have a client that runs across all platforms!
  136 +- 🚀 v2.7 let's share conversations as image, or share to ShareGPT!
  137 +- 🚀 v2.0 is released, now you can create prompt templates, turn your ideas into reality! Read this: [ChatGPT Prompt Engineering Tips: Zero, One and Few Shot Prompting](https://www.allabtai.com/prompt-engineering-tips-zero-one-and-few-shot-prompting/).
  138 +
  139 +## Get Started
  140 +
  141 +1. Get [OpenAI API Key](https://platform.openai.com/account/api-keys);
  142 +2. Click
  143 + [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYidadaa%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=chatgpt-next-web&repository-name=ChatGPT-Next-Web), remember that `CODE` is your page password;
  144 +3. Enjoy :)
  145 +
  146 +## FAQ
  147 +
  148 +[English > FAQ](./docs/faq-en.md)
  149 +
  150 +## Keep Updated
  151 +
  152 +If you have deployed your own project with just one click following the steps above, you may encounter the issue of "Updates Available" constantly showing up. This is because Vercel will create a new project for you by default instead of forking this project, resulting in the inability to detect updates correctly.
  153 +
  154 +We recommend that you follow the steps below to re-deploy:
  155 +
  156 +- Delete the original repository;
  157 +- Use the fork button in the upper right corner of the page to fork this project;
  158 +- Choose and deploy in Vercel again, [please see the detailed tutorial](./docs/vercel-cn.md).
  159 +
  160 +### Enable Automatic Updates
  161 +
  162 +> If you encounter a failure of Upstream Sync execution, please [manually update code](./README.md#manually-updating-code).
  163 +
  164 +After forking the project, due to the limitations imposed by GitHub, you need to manually enable Workflows and Upstream Sync Action on the Actions page of the forked project. Once enabled, automatic updates will be scheduled every hour:
  165 +
  166 +![Automatic Updates](./docs/images/enable-actions.jpg)
  167 +
  168 +![Enable Automatic Updates](./docs/images/enable-actions-sync.jpg)
  169 +
  170 +### Manually Updating Code
  171 +
  172 +If you want to update instantly, you can check out the [GitHub documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork) to learn how to synchronize a forked project with upstream code.
  173 +
  174 +You can star or watch this project or follow author to get release notifications in time.
  175 +
  176 +## Access Password
  177 +
  178 +This project provides limited access control. Please add an environment variable named `CODE` on the vercel environment variables page. The value should be passwords separated by comma like this:
  179 +
  180 +```
  181 +code1,code2,code3
  182 +```
  183 +
  184 +After adding or modifying this environment variable, please redeploy the project for the changes to take effect.
  185 +
  186 +## Environment Variables
  187 +
  188 +### `CODE` (optional)
  189 +
  190 +Access password, separated by comma.
  191 +
  192 +### `OPENAI_API_KEY` (required)
  193 +
  194 +Your openai api key, join multiple api keys with comma.
  195 +
  196 +### `BASE_URL` (optional)
  197 +
  198 +> Default: `https://api.openai.com`
  199 +
  200 +> Examples: `http://your-openai-proxy.com`
  201 +
  202 +Override openai api request base url.
  203 +
  204 +### `OPENAI_ORG_ID` (optional)
  205 +
  206 +Specify OpenAI organization ID.
  207 +
  208 +### `AZURE_URL` (optional)
  209 +
  210 +> Example: https://{azure-resource-url}/openai
  211 +
  212 +Azure deploy url.
  213 +
  214 +### `AZURE_API_KEY` (optional)
  215 +
  216 +Azure Api Key.
  217 +
  218 +### `AZURE_API_VERSION` (optional)
  219 +
  220 +Azure Api Version, find it at [Azure Documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#chat-completions).
  221 +
  222 +### `GOOGLE_API_KEY` (optional)
  223 +
  224 +Google Gemini Pro Api Key.
  225 +
  226 +### `GOOGLE_URL` (optional)
  227 +
  228 +Google Gemini Pro Api Url.
  229 +
  230 +### `ANTHROPIC_API_KEY` (optional)
  231 +
  232 +anthropic claude Api Key.
  233 +
  234 +### `ANTHROPIC_API_VERSION` (optional)
  235 +
  236 +anthropic claude Api version.
  237 +
  238 +### `ANTHROPIC_URL` (optional)
  239 +
  240 +anthropic claude Api Url.
  241 +
  242 +### `BAIDU_API_KEY` (optional)
  243 +
  244 +Baidu Api Key.
  245 +
  246 +### `BAIDU_SECRET_KEY` (optional)
  247 +
  248 +Baidu Secret Key.
  249 +
  250 +### `BAIDU_URL` (optional)
  251 +
  252 +Baidu Api Url.
  253 +
  254 +### `BYTEDANCE_API_KEY` (optional)
  255 +
  256 +ByteDance Api Key.
  257 +
  258 +### `BYTEDANCE_URL` (optional)
  259 +
  260 +ByteDance Api Url.
  261 +
  262 +### `ALIBABA_API_KEY` (optional)
  263 +
  264 +Alibaba Cloud Api Key.
  265 +
  266 +### `ALIBABA_URL` (optional)
  267 +
  268 +Alibaba Cloud Api Url.
  269 +
  270 +### `IFLYTEK_URL` (Optional)
  271 +
  272 +iflytek Api Url.
  273 +
  274 +### `IFLYTEK_API_KEY` (Optional)
  275 +
  276 +iflytek Api Key.
  277 +
  278 +### `IFLYTEK_API_SECRET` (Optional)
  279 +
  280 +iflytek Api Secret.
  281 +
  282 +### `CHATGLM_API_KEY` (optional)
  283 +
  284 +ChatGLM Api Key.
  285 +
  286 +### `CHATGLM_URL` (optional)
  287 +
  288 +ChatGLM Api Url.
  289 +
  290 +### `DEEPSEEK_API_KEY` (optional)
  291 +
  292 +DeepSeek Api Key.
  293 +
  294 +### `DEEPSEEK_URL` (optional)
  295 +
  296 +DeepSeek Api Url.
  297 +
  298 +### `HIDE_USER_API_KEY` (optional)
  299 +
  300 +> Default: Empty
  301 +
  302 +If you do not want users to input their own API key, set this value to 1.
  303 +
  304 +### `DISABLE_GPT4` (optional)
  305 +
  306 +> Default: Empty
  307 +
  308 +If you do not want users to use GPT-4, set this value to 1.
  309 +
  310 +### `ENABLE_BALANCE_QUERY` (optional)
  311 +
  312 +> Default: Empty
  313 +
  314 +If you do want users to query balance, set this value to 1.
  315 +
  316 +### `DISABLE_FAST_LINK` (optional)
  317 +
  318 +> Default: Empty
  319 +
  320 +If you want to disable parse settings from url, set this to 1.
  321 +
  322 +### `CUSTOM_MODELS` (optional)
  323 +
  324 +> Default: Empty
  325 +> Example: `+llama,+claude-2,-gpt-3.5-turbo,gpt-4-1106-preview=gpt-4-turbo` means add `llama, claude-2` to model list, and remove `gpt-3.5-turbo` from list, and display `gpt-4-1106-preview` as `gpt-4-turbo`.
  326 +
  327 +To control custom models, use `+` to add a custom model, use `-` to hide a model, use `name=displayName` to customize model name, separated by comma.
  328 +
  329 +User `-all` to disable all default models, `+all` to enable all default models.
  330 +
  331 +For Azure: use `modelName@Azure=deploymentName` to customize model name and deployment name.
  332 +> Example: `+gpt-3.5-turbo@Azure=gpt35` will show option `gpt35(Azure)` in model list.
  333 +> If you only can use Azure model, `-all,+gpt-3.5-turbo@Azure=gpt35` will `gpt35(Azure)` the only option in model list.
  334 +
  335 +For ByteDance: use `modelName@bytedance=deploymentName` to customize model name and deployment name.
  336 +> Example: `+Doubao-lite-4k@bytedance=ep-xxxxx-xxx` will show option `Doubao-lite-4k(ByteDance)` in model list.
  337 +
  338 +### `DEFAULT_MODEL` (optional)
  339 +
  340 +Change default model
  341 +
  342 +### `VISION_MODELS` (optional)
  343 +
  344 +> Default: Empty
  345 +> Example: `gpt-4-vision,claude-3-opus,my-custom-model` means add vision capabilities to these models in addition to the default pattern matches (which detect models containing keywords like "vision", "claude-3", "gemini-1.5", etc).
  346 +
  347 +Add additional models to have vision capabilities, beyond the default pattern matching. Multiple models should be separated by commas.
  348 +
  349 +### `WHITE_WEBDAV_ENDPOINTS` (optional)
  350 +
  351 +You can use this option if you want to increase the number of webdav service addresses you are allowed to access, as required by the format:
  352 +- Each address must be a complete endpoint
  353 +> `https://xxxx/yyy`
  354 +- Multiple addresses are connected by ', '
  355 +
  356 +### `DEFAULT_INPUT_TEMPLATE` (optional)
  357 +
  358 +Customize the default template used to initialize the User Input Preprocessing configuration item in Settings.
  359 +
  360 +### `STABILITY_API_KEY` (optional)
  361 +
  362 +Stability API key.
  363 +
  364 +### `STABILITY_URL` (optional)
  365 +
  366 +Customize Stability API url.
  367 +
  368 +
  369 +### `ENABLE_MCP` (optional)
  370 +
  371 +Enable MCP(Model Context Protocol)Feature
  372 +
  373 +### `SILICONFLOW_API_KEY` (optional)
  374 +
  375 +SiliconFlow API Key.
  376 +
  377 +### `SILICONFLOW_URL` (optional)
  378 +
  379 +SiliconFlow API URL.
  380 +
  381 +## Requirements
  382 +
  383 +NodeJS >= 18, Docker >= 20
  384 +
  385 +## Development
  386 +
  387 +
  388 +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web)
  389 +
  390 +Before starting development, you must create a new `.env.local` file at project root, and place your api key into it:
  391 +
  392 +```
  393 +OPENAI_API_KEY=<your api key here>
  394 +
  395 +# if you are not able to access openai service, use this BASE_URL
  396 +BASE_URL=https://chatgpt1.nextweb.fun/api/proxy
  397 +```
  398 +
  399 +### Local Development
  400 +
  401 +```shell
  402 +# 1. install nodejs and yarn first
  403 +# 2. config local env vars in `.env.local`
  404 +# 3. run
  405 +yarn install
  406 +yarn dev
  407 +```
  408 +
  409 +## Deployment
  410 +
  411 +
  412 +### Docker (Recommended)
  413 +
  414 +```shell
  415 +docker pull yidadaa/chatgpt-next-web
  416 +
  417 +docker run -d -p 3000:3000 \
  418 + -e OPENAI_API_KEY=sk-xxxx \
  419 + -e CODE=your-password \
  420 + yidadaa/chatgpt-next-web
  421 +```
  422 +
  423 +You can start service behind a proxy:
  424 +
  425 +```shell
  426 +docker run -d -p 3000:3000 \
  427 + -e OPENAI_API_KEY=sk-xxxx \
  428 + -e CODE=your-password \
  429 + -e PROXY_URL=http://localhost:7890 \
  430 + yidadaa/chatgpt-next-web
  431 +```
  432 +
  433 +If your proxy needs password, use:
  434 +
  435 +```shell
  436 +-e PROXY_URL="http://127.0.0.1:7890 user pass"
  437 +```
  438 +
  439 +If enable MCP, use:
  440 +
  441 +```
  442 +docker run -d -p 3000:3000 \
  443 + -e OPENAI_API_KEY=sk-xxxx \
  444 + -e CODE=your-password \
  445 + -e ENABLE_MCP=true \
  446 + yidadaa/chatgpt-next-web
  447 +```
  448 +
  449 +### Shell
  450 +
  451 +```shell
  452 +bash <(curl -s https://raw.githubusercontent.com/Yidadaa/ChatGPT-Next-Web/main/scripts/setup.sh)
  453 +```
  454 +
  455 +## Synchronizing Chat Records (UpStash)
  456 +
  457 +| [简体中文](./docs/synchronise-chat-logs-cn.md) | [English](./docs/synchronise-chat-logs-en.md) | [Italiano](./docs/synchronise-chat-logs-es.md) | [日本語](./docs/synchronise-chat-logs-ja.md) | [한국어](./docs/synchronise-chat-logs-ko.md)
  458 +
  459 +## Documentation
  460 +
  461 +> Please go to the [docs][./docs] directory for more documentation instructions.
  462 +
  463 +- [Deploy with cloudflare (Deprecated)](./docs/cloudflare-pages-en.md)
  464 +- [Frequent Ask Questions](./docs/faq-en.md)
  465 +- [How to add a new translation](./docs/translation.md)
  466 +- [How to use Vercel (No English)](./docs/vercel-cn.md)
  467 +- [User Manual (Only Chinese, WIP)](./docs/user-manual-cn.md)
  468 +
  469 +
  470 +
  471 +## Translation
  472 +
  473 +If you want to add a new translation, read this [document](./docs/translation.md).
  474 +
  475 +## Donation
  476 +
  477 +[Buy Me a Coffee](https://www.buymeacoffee.com/yidadaa)
  478 +
  479 +## Special Thanks
  480 +
  481 +
  482 +
  483 +### Contributors
  484 +
  485 +<a href="https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/graphs/contributors">
  486 + <img src="https://contrib.rocks/image?repo=ChatGPTNextWeb/ChatGPT-Next-Web" />
  487 +</a>
  488 +
  489 +## LICENSE
  490 +
  491 +[MIT](https://opensource.org/license/mit/)
  1 +<div align="center">
  2 +
  3 +<a href='#企业版'>
  4 + <img src="./docs/images/ent.svg" alt="icon"/>
  5 +</a>
  6 +
  7 +<h1 align="center">NextChat</h1>
  8 +
  9 +一键免费部署你的私人 ChatGPT 网页应用,支持 Claude, GPT4 & Gemini Pro 模型。
  10 +
  11 +[NextChatAI](https://nextchat.club?utm_source=readme) / [企业版](#%E4%BC%81%E4%B8%9A%E7%89%88) / [演示 Demo](https://chat-gpt-next-web.vercel.app/) / [反馈 Issues](https://github.com/Yidadaa/ChatGPT-Next-Web/issues) / [加入 Discord](https://discord.gg/zrhvHCr79N)
  12 +
  13 +[<img src="https://vercel.com/button" alt="Deploy on Zeabur" height="30">](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FChatGPTNextWeb%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=nextchat&repository-name=NextChat) [<img src="https://zeabur.com/button.svg" alt="Deploy on Zeabur" height="30">](https://zeabur.com/templates/ZBUEFA) [<img src="https://gitpod.io/button/open-in-gitpod.svg" alt="Open in Gitpod" height="30">](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web)
  14 +
  15 +</div>
  16 +
  17 +## 企业版
  18 +
  19 +满足您公司私有化部署和定制需求
  20 +- **品牌定制**:企业量身定制 VI/UI,与企业品牌形象无缝契合
  21 +- **资源集成**:由企业管理人员统一配置和管理数十种 AI 资源,团队成员开箱即用
  22 +- **权限管理**:成员权限、资源权限、知识库权限层级分明,企业级 Admin Panel 统一控制
  23 +- **知识接入**:企业内部知识库与 AI 能力相结合,比通用 AI 更贴近企业自身业务需求
  24 +- **安全审计**:自动拦截敏感提问,支持追溯全部历史对话记录,让 AI 也能遵循企业信息安全规范
  25 +- **私有部署**:企业级私有部署,支持各类主流私有云部署,确保数据安全和隐私保护
  26 +- **持续更新**:提供多模态、智能体等前沿能力持续更新升级服务,常用常新、持续先进
  27 +
  28 +企业版咨询: **business@nextchat.dev**
  29 +
  30 +<img width="300" src="https://github.com/user-attachments/assets/bb29a11d-ff75-48a8-b1f8-d2d7238cf987">
  31 +
  32 +
  33 +## 开始使用
  34 +
  35 +1. 准备好你的 [OpenAI API Key](https://platform.openai.com/account/api-keys);
  36 +2. 点击右侧按钮开始部署:
  37 + [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYidadaa%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&env=GOOGLE_API_KEY&project-name=chatgpt-next-web&repository-name=ChatGPT-Next-Web),直接使用 Github 账号登录即可,记得在环境变量页填入 API Key 和[页面访问密码](#配置页面访问密码) CODE;
  38 +3. 部署完毕后,即可开始使用;
  39 +4. (可选)[绑定自定义域名](https://vercel.com/docs/concepts/projects/domains/add-a-domain):Vercel 分配的域名 DNS 在某些区域被污染了,绑定自定义域名即可直连。
  40 +
  41 +<div align="center">
  42 +
  43 +![主界面](./docs/images/cover.png)
  44 +
  45 +</div>
  46 +
  47 +## 保持更新
  48 +
  49 +如果你按照上述步骤一键部署了自己的项目,可能会发现总是提示“存在更新”的问题,这是由于 Vercel 会默认为你创建一个新项目而不是 fork 本项目,这会导致无法正确地检测更新。
  50 +推荐你按照下列步骤重新部署:
  51 +
  52 +- 删除掉原先的仓库;
  53 +- 使用页面右上角的 fork 按钮,fork 本项目;
  54 +- 在 Vercel 重新选择并部署,[请查看详细教程](./docs/vercel-cn.md#如何新建项目)
  55 +
  56 +### 打开自动更新
  57 +
  58 +> 如果你遇到了 Upstream Sync 执行错误,请[手动 Sync Fork 一次](./README_CN.md#手动更新代码)!
  59 +
  60 +当你 fork 项目之后,由于 Github 的限制,需要手动去你 fork 后的项目的 Actions 页面启用 Workflows,并启用 Upstream Sync Action,启用之后即可开启每小时定时自动更新:
  61 +
  62 +![自动更新](./docs/images/enable-actions.jpg)
  63 +
  64 +![启用自动更新](./docs/images/enable-actions-sync.jpg)
  65 +
  66 +### 手动更新代码
  67 +
  68 +如果你想让手动立即更新,可以查看 [Github 的文档](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork) 了解如何让 fork 的项目与上游代码同步。
  69 +
  70 +你可以 star/watch 本项目或者 follow 作者来及时获得新功能更新通知。
  71 +
  72 +## 配置页面访问密码
  73 +
  74 +> 配置密码后,用户需要在设置页手动填写访问码才可以正常聊天,否则会通过消息提示未授权状态。
  75 +
  76 +> **警告**:请务必将密码的位数设置得足够长,最好 7 位以上,否则[会被爆破](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/518)。
  77 +
  78 +本项目提供有限的权限控制功能,请在 Vercel 项目控制面板的环境变量页增加名为 `CODE` 的环境变量,值为用英文逗号分隔的自定义密码:
  79 +
  80 +```
  81 +code1,code2,code3
  82 +```
  83 +
  84 +增加或修改该环境变量后,请**重新部署**项目使改动生效。
  85 +
  86 +## 环境变量
  87 +
  88 +> 本项目大多数配置项都通过环境变量来设置,教程:[如何修改 Vercel 环境变量](./docs/vercel-cn.md)。
  89 +
  90 +### `OPENAI_API_KEY` (必填项)
  91 +
  92 +OpenAI 密钥,你在 openai 账户页面申请的 api key,使用英文逗号隔开多个 key,这样可以随机轮询这些 key。
  93 +
  94 +### `CODE` (可选)
  95 +
  96 +访问密码,可选,可以使用逗号隔开多个密码。
  97 +
  98 +**警告**:如果不填写此项,则任何人都可以直接使用你部署后的网站,可能会导致你的 token 被急速消耗完毕,建议填写此选项。
  99 +
  100 +### `BASE_URL` (可选)
  101 +
  102 +> Default: `https://api.openai.com`
  103 +
  104 +> Examples: `http://your-openai-proxy.com`
  105 +
  106 +OpenAI 接口代理 URL,如果你手动配置了 openai 接口代理,请填写此选项。
  107 +
  108 +> 如果遇到 ssl 证书问题,请将 `BASE_URL` 的协议设置为 http。
  109 +
  110 +### `OPENAI_ORG_ID` (可选)
  111 +
  112 +指定 OpenAI 中的组织 ID。
  113 +
  114 +### `AZURE_URL` (可选)
  115 +
  116 +> 形如:https://{azure-resource-url}/openai
  117 +
  118 +Azure 部署地址。
  119 +
  120 +### `AZURE_API_KEY` (可选)
  121 +
  122 +Azure 密钥。
  123 +
  124 +### `AZURE_API_VERSION` (可选)
  125 +
  126 +Azure Api 版本,你可以在这里找到:[Azure 文档](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#chat-completions)
  127 +
  128 +### `GOOGLE_API_KEY` (可选)
  129 +
  130 +Google Gemini Pro 密钥.
  131 +
  132 +### `GOOGLE_URL` (可选)
  133 +
  134 +Google Gemini Pro Api Url.
  135 +
  136 +### `ANTHROPIC_API_KEY` (可选)
  137 +
  138 +anthropic claude Api Key.
  139 +
  140 +### `ANTHROPIC_API_VERSION` (可选)
  141 +
  142 +anthropic claude Api version.
  143 +
  144 +### `ANTHROPIC_URL` (可选)
  145 +
  146 +anthropic claude Api Url.
  147 +
  148 +### `BAIDU_API_KEY` (可选)
  149 +
  150 +Baidu Api Key.
  151 +
  152 +### `BAIDU_SECRET_KEY` (可选)
  153 +
  154 +Baidu Secret Key.
  155 +
  156 +### `BAIDU_URL` (可选)
  157 +
  158 +Baidu Api Url.
  159 +
  160 +### `BYTEDANCE_API_KEY` (可选)
  161 +
  162 +ByteDance Api Key.
  163 +
  164 +### `BYTEDANCE_URL` (可选)
  165 +
  166 +ByteDance Api Url.
  167 +
  168 +### `ALIBABA_API_KEY` (可选)
  169 +
  170 +阿里云(千问)Api Key.
  171 +
  172 +### `ALIBABA_URL` (可选)
  173 +
  174 +阿里云(千问)Api Url.
  175 +
  176 +### `IFLYTEK_URL` (可选)
  177 +
  178 +讯飞星火Api Url.
  179 +
  180 +### `IFLYTEK_API_KEY` (可选)
  181 +
  182 +讯飞星火Api Key.
  183 +
  184 +### `IFLYTEK_API_SECRET` (可选)
  185 +
  186 +讯飞星火Api Secret.
  187 +
  188 +### `CHATGLM_API_KEY` (可选)
  189 +
  190 +ChatGLM Api Key.
  191 +
  192 +### `CHATGLM_URL` (可选)
  193 +
  194 +ChatGLM Api Url.
  195 +
  196 +### `DEEPSEEK_API_KEY` (可选)
  197 +
  198 +DeepSeek Api Key.
  199 +
  200 +### `DEEPSEEK_URL` (可选)
  201 +
  202 +DeepSeek Api Url.
  203 +
  204 +
  205 +### `HIDE_USER_API_KEY` (可选)
  206 +
  207 +如果你不想让用户自行填入 API Key,将此环境变量设置为 1 即可。
  208 +
  209 +### `DISABLE_GPT4` (可选)
  210 +
  211 +如果你不想让用户使用 GPT-4,将此环境变量设置为 1 即可。
  212 +
  213 +### `ENABLE_BALANCE_QUERY` (可选)
  214 +
  215 +如果你想启用余额查询功能,将此环境变量设置为 1 即可。
  216 +
  217 +### `DISABLE_FAST_LINK` (可选)
  218 +
  219 +如果你想禁用从链接解析预制设置,将此环境变量设置为 1 即可。
  220 +
  221 +### `WHITE_WEBDAV_ENDPOINTS` (可选)
  222 +
  223 +如果你想增加允许访问的webdav服务地址,可以使用该选项,格式要求:
  224 +- 每一个地址必须是一个完整的 endpoint
  225 +> `https://xxxx/xxx`
  226 +- 多个地址以`,`相连
  227 +
  228 +### `CUSTOM_MODELS` (可选)
  229 +
  230 +> 示例:`+qwen-7b-chat,+glm-6b,-gpt-3.5-turbo,gpt-4-1106-preview=gpt-4-turbo` 表示增加 `qwen-7b-chat` 和 `glm-6b` 到模型列表,而从列表中删除 `gpt-3.5-turbo`,并将 `gpt-4-1106-preview` 模型名字展示为 `gpt-4-turbo`。
  231 +> 如果你想先禁用所有模型,再启用指定模型,可以使用 `-all,+gpt-3.5-turbo`,则表示仅启用 `gpt-3.5-turbo`
  232 +
  233 +用来控制模型列表,使用 `+` 增加一个模型,使用 `-` 来隐藏一个模型,使用 `模型名=展示名` 来自定义模型的展示名,用英文逗号隔开。
  234 +
  235 +在Azure的模式下,支持使用`modelName@Azure=deploymentName`的方式配置模型名称和部署名称(deploy-name)
  236 +> 示例:`+gpt-3.5-turbo@Azure=gpt35`这个配置会在模型列表显示一个`gpt35(Azure)`的选项。
  237 +> 如果你只能使用Azure模式,那么设置 `-all,+gpt-3.5-turbo@Azure=gpt35` 则可以让对话的默认使用 `gpt35(Azure)`
  238 +
  239 +在ByteDance的模式下,支持使用`modelName@bytedance=deploymentName`的方式配置模型名称和部署名称(deploy-name)
  240 +> 示例: `+Doubao-lite-4k@bytedance=ep-xxxxx-xxx`这个配置会在模型列表显示一个`Doubao-lite-4k(ByteDance)`的选项
  241 +
  242 +
  243 +### `DEFAULT_MODEL` (可选)
  244 +
  245 +更改默认模型
  246 +
  247 +### `VISION_MODELS` (可选)
  248 +
  249 +> 默认值:空
  250 +> 示例:`gpt-4-vision,claude-3-opus,my-custom-model` 表示为这些模型添加视觉能力,作为对默认模式匹配的补充(默认会检测包含"vision"、"claude-3"、"gemini-1.5"等关键词的模型)。
  251 +
  252 +在默认模式匹配之外,添加更多具有视觉能力的模型。多个模型用逗号分隔。
  253 +
  254 +### `DEFAULT_INPUT_TEMPLATE` (可选)
  255 +
  256 +自定义默认的 template,用于初始化『设置』中的『用户输入预处理』配置项
  257 +
  258 +### `STABILITY_API_KEY` (optional)
  259 +
  260 +Stability API密钥
  261 +
  262 +### `STABILITY_URL` (optional)
  263 +
  264 +自定义的Stability API请求地址
  265 +
  266 +### `ENABLE_MCP` (optional)
  267 +
  268 +启用MCP(Model Context Protocol)功能
  269 +
  270 +### `SILICONFLOW_API_KEY` (optional)
  271 +
  272 +SiliconFlow API Key.
  273 +
  274 +### `SILICONFLOW_URL` (optional)
  275 +
  276 +SiliconFlow API URL.
  277 +
  278 +## 开发
  279 +
  280 +点击下方按钮,开始二次开发:
  281 +
  282 +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web)
  283 +
  284 +在开始写代码之前,需要在项目根目录新建一个 `.env.local` 文件,里面填入环境变量:
  285 +
  286 +```
  287 +OPENAI_API_KEY=<your api key here>
  288 +
  289 +# 中国大陆用户,可以使用本项目自带的代理进行开发,你也可以自由选择其他代理地址
  290 +BASE_URL=https://b.nextweb.fun/api/proxy
  291 +```
  292 +
  293 +### 本地开发
  294 +
  295 +1. 安装 nodejs 18 和 yarn,具体细节请询问 ChatGPT;
  296 +2. 执行 `yarn install && yarn dev` 即可。⚠️ 注意:此命令仅用于本地开发,不要用于部署!
  297 +3. 如果你想本地部署,请使用 `yarn install && yarn build && yarn start` 命令,你可以配合 pm2 来守护进程,防止被杀死,详情询问 ChatGPT。
  298 +
  299 +## 部署
  300 +
  301 +### 宝塔面板部署
  302 +> [简体中文 > 如何通过宝塔一键部署](./docs/bt-cn.md)
  303 +
  304 +### 容器部署 (推荐)
  305 +
  306 +> Docker 版本需要在 20 及其以上,否则会提示找不到镜像。
  307 +
  308 +> ⚠️ 注意:docker 版本在大多数时间都会落后最新的版本 1 到 2 天,所以部署后会持续出现“存在更新”的提示,属于正常现象。
  309 +
  310 +```shell
  311 +docker pull yidadaa/chatgpt-next-web
  312 +
  313 +docker run -d -p 3000:3000 \
  314 + -e OPENAI_API_KEY=sk-xxxx \
  315 + -e CODE=页面访问密码 \
  316 + yidadaa/chatgpt-next-web
  317 +```
  318 +
  319 +你也可以指定 proxy:
  320 +
  321 +```shell
  322 +docker run -d -p 3000:3000 \
  323 + -e OPENAI_API_KEY=sk-xxxx \
  324 + -e CODE=页面访问密码 \
  325 + --net=host \
  326 + -e PROXY_URL=http://127.0.0.1:7890 \
  327 + yidadaa/chatgpt-next-web
  328 +```
  329 +
  330 +如需启用 MCP 功能,可以使用:
  331 +
  332 +```shell
  333 +docker run -d -p 3000:3000 \
  334 + -e OPENAI_API_KEY=sk-xxxx \
  335 + -e CODE=页面访问密码 \
  336 + -e ENABLE_MCP=true \
  337 + yidadaa/chatgpt-next-web
  338 +```
  339 +
  340 +如果你的本地代理需要账号密码,可以使用:
  341 +
  342 +```shell
  343 +-e PROXY_URL="http://127.0.0.1:7890 user password"
  344 +```
  345 +
  346 +如果你需要指定其他环境变量,请自行在上述命令中增加 `-e 环境变量=环境变量值` 来指定。
  347 +
  348 +### 本地部署
  349 +
  350 +在控制台运行下方命令:
  351 +
  352 +```shell
  353 +bash <(curl -s https://raw.githubusercontent.com/Yidadaa/ChatGPT-Next-Web/main/scripts/setup.sh)
  354 +```
  355 +
  356 +⚠️ 注意:如果你安装过程中遇到了问题,请使用 docker 部署。
  357 +
  358 +## 鸣谢
  359 +
  360 +### 捐赠者
  361 +
  362 +> 见英文版。
  363 +
  364 +### 贡献者
  365 +
  366 +[见项目贡献者列表](https://github.com/Yidadaa/ChatGPT-Next-Web/graphs/contributors)
  367 +
  368 +### 相关项目
  369 +
  370 +- [one-api](https://github.com/songquanpeng/one-api): 一站式大模型额度管理平台,支持市面上所有主流大语言模型
  371 +
  372 +## 开源协议
  373 +
  374 +[MIT](https://opensource.org/license/mit/)
  1 +<div align="center">
  2 +<img src="./docs/images/ent.svg" alt="プレビュー"/>
  3 +
  4 +<h1 align="center">NextChat</h1>
  5 +
  6 +ワンクリックで無料であなた専用の ChatGPT ウェブアプリをデプロイ。GPT3、GPT4 & Gemini Pro モデルをサポート。
  7 +
  8 +[NextChatAI](https://nextchat.club?utm_source=readme) / [企業版](#企業版) / [デモ](https://chat-gpt-next-web.vercel.app/) / [フィードバック](https://github.com/Yidadaa/ChatGPT-Next-Web/issues) / [Discordに参加](https://discord.gg/zrhvHCr79N)
  9 +
  10 +[<img src="https://vercel.com/button" alt="Zeaburでデプロイ" height="30">](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FChatGPTNextWeb%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=nextchat&repository-name=NextChat) [<img src="https://zeabur.com/button.svg" alt="Zeaburでデプロイ" height="30">](https://zeabur.com/templates/ZBUEFA) [<img src="https://gitpod.io/button/open-in-gitpod.svg" alt="Gitpodで開く" height="30">](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web)
  11 +
  12 +
  13 +</div>
  14 +
  15 +## 企業版
  16 +
  17 +あなたの会社のプライベートデプロイとカスタマイズのニーズに応える
  18 +- **ブランドカスタマイズ**:企業向けに特別に設計された VI/UI、企業ブランドイメージとシームレスにマッチ
  19 +- **リソース統合**:企業管理者が数十種類のAIリソースを統一管理、チームメンバーはすぐに使用可能
  20 +- **権限管理**:メンバーの権限、リソースの権限、ナレッジベースの権限を明確にし、企業レベルのAdmin Panelで統一管理
  21 +- **知識の統合**:企業内部のナレッジベースとAI機能を結びつけ、汎用AIよりも企業自身の業務ニーズに近づける
  22 +- **セキュリティ監査**:機密質問を自動的にブロックし、すべての履歴対話を追跡可能にし、AIも企業の情報セキュリティ基準に従わせる
  23 +- **プライベートデプロイ**:企業レベルのプライベートデプロイ、主要なプライベートクラウドデプロイをサポートし、データのセキュリティとプライバシーを保護
  24 +- **継続的な更新**:マルチモーダル、エージェントなどの最先端機能を継続的に更新し、常に最新であり続ける
  25 +
  26 +企業版のお問い合わせ: **business@nextchat.dev**
  27 +
  28 +
  29 +## 始めに
  30 +
  31 +1. [OpenAI API Key](https://platform.openai.com/account/api-keys)を準備する;
  32 +2. 右側のボタンをクリックしてデプロイを開始:
  33 + [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYidadaa%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&env=GOOGLE_API_KEY&project-name=chatgpt-next-web&repository-name=ChatGPT-Next-Web) 、GitHubアカウントで直接ログインし、環境変数ページにAPI Keyと[ページアクセスパスワード](#設定ページアクセスパスワード) CODEを入力してください;
  34 +3. デプロイが完了したら、すぐに使用を開始できます;
  35 +4. (オプション)[カスタムドメインをバインド](https://vercel.com/docs/concepts/projects/domains/add-a-domain):Vercelが割り当てたドメインDNSは一部の地域で汚染されているため、カスタムドメインをバインドすると直接接続できます。
  36 +
  37 +<div align="center">
  38 +
  39 +![メインインターフェース](./docs/images/cover.png)
  40 +
  41 +</div>
  42 +
  43 +
  44 +## 更新を維持する
  45 +
  46 +もし上記の手順に従ってワンクリックでプロジェクトをデプロイした場合、「更新があります」というメッセージが常に表示されることがあります。これは、Vercel がデフォルトで新しいプロジェクトを作成するためで、本プロジェクトを fork していないことが原因です。そのため、正しく更新を検出できません。
  47 +
  48 +以下の手順に従って再デプロイすることをお勧めします:
  49 +
  50 +- 元のリポジトリを削除する
  51 +- ページ右上の fork ボタンを使って、本プロジェクトを fork する
  52 +- Vercel で再度選択してデプロイする、[詳細な手順はこちらを参照してください](./docs/vercel-ja.md)
  53 +
  54 +
  55 +### 自動更新を開く
  56 +
  57 +> Upstream Sync の実行エラーが発生した場合は、[手動で Sync Fork](./README_JA.md#手動でコードを更新する) してください!
  58 +
  59 +プロジェクトを fork した後、GitHub の制限により、fork 後のプロジェクトの Actions ページで Workflows を手動で有効にし、Upstream Sync Action を有効にする必要があります。有効化後、毎時の定期自動更新が可能になります:
  60 +
  61 +![自動更新](./docs/images/enable-actions.jpg)
  62 +
  63 +![自動更新を有効にする](./docs/images/enable-actions-sync.jpg)
  64 +
  65 +
  66 +### 手動でコードを更新する
  67 +
  68 +手動で即座に更新したい場合は、[GitHub のドキュメント](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork)を参照して、fork したプロジェクトを上流のコードと同期する方法を確認してください。
  69 +
  70 +このプロジェクトをスターまたはウォッチしたり、作者をフォローすることで、新機能の更新通知をすぐに受け取ることができます。
  71 +
  72 +
  73 +
  74 +## ページアクセスパスワードを設定する
  75 +
  76 +> パスワードを設定すると、ユーザーは設定ページでアクセスコードを手動で入力しない限り、通常のチャットができず、未承認の状態であることを示すメッセージが表示されます。
  77 +
  78 +> **警告**:パスワードの桁数は十分に長く設定してください。7桁以上が望ましいです。さもないと、[ブルートフォース攻撃を受ける可能性があります](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/518)。
  79 +
  80 +このプロジェクトは限られた権限管理機能を提供しています。Vercel プロジェクトのコントロールパネルで、環境変数ページに `CODE` という名前の環境変数を追加し、値をカンマで区切ったカスタムパスワードに設定してください:
  81 +
  82 +```
  83 +code1,code2,code3
  84 +```
  85 +
  86 +この環境変数を追加または変更した後、**プロジェクトを再デプロイ**して変更を有効にしてください。
  87 +
  88 +
  89 +## 環境変数
  90 +
  91 +> 本プロジェクトのほとんどの設定は環境変数で行います。チュートリアル:[Vercel の環境変数を変更する方法](./docs/vercel-ja.md)。
  92 +
  93 +### `OPENAI_API_KEY` (必須)
  94 +
  95 +OpenAI の API キー。OpenAI アカウントページで申請したキーをカンマで区切って複数設定できます。これにより、ランダムにキーが選択されます。
  96 +
  97 +### `CODE` (オプション)
  98 +
  99 +アクセスパスワード。カンマで区切って複数設定可能。
  100 +
  101 +**警告**:この項目を設定しないと、誰でもデプロイしたウェブサイトを利用でき、トークンが急速に消耗する可能性があるため、設定をお勧めします。
  102 +
  103 +### `BASE_URL` (オプション)
  104 +
  105 +> デフォルト: `https://api.openai.com`
  106 +
  107 +> 例: `http://your-openai-proxy.com`
  108 +
  109 +OpenAI API のプロキシ URL。手動で OpenAI API のプロキシを設定している場合はこのオプションを設定してください。
  110 +
  111 +> SSL 証明書の問題がある場合は、`BASE_URL` のプロトコルを http に設定してください。
  112 +
  113 +### `OPENAI_ORG_ID` (オプション)
  114 +
  115 +OpenAI の組織 ID を指定します。
  116 +
  117 +### `AZURE_URL` (オプション)
  118 +
  119 +> 形式: https://{azure-resource-url}/openai/deployments/{deploy-name}
  120 +> `CUSTOM_MODELS` で `displayName` 形式で {deploy-name} を設定した場合、`AZURE_URL` から {deploy-name} を省略できます。
  121 +
  122 +Azure のデプロイ URL。
  123 +
  124 +### `AZURE_API_KEY` (オプション)
  125 +
  126 +Azure の API キー。
  127 +
  128 +### `AZURE_API_VERSION` (オプション)
  129 +
  130 +Azure API バージョン。[Azure ドキュメント](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#chat-completions)で確認できます。
  131 +
  132 +### `GOOGLE_API_KEY` (オプション)
  133 +
  134 +Google Gemini Pro API キー。
  135 +
  136 +### `GOOGLE_URL` (オプション)
  137 +
  138 +Google Gemini Pro API の URL。
  139 +
  140 +### `ANTHROPIC_API_KEY` (オプション)
  141 +
  142 +Anthropic Claude API キー。
  143 +
  144 +### `ANTHROPIC_API_VERSION` (オプション)
  145 +
  146 +Anthropic Claude API バージョン。
  147 +
  148 +### `ANTHROPIC_URL` (オプション)
  149 +
  150 +Anthropic Claude API の URL。
  151 +
  152 +### `BAIDU_API_KEY` (オプション)
  153 +
  154 +Baidu API キー。
  155 +
  156 +### `BAIDU_SECRET_KEY` (オプション)
  157 +
  158 +Baidu シークレットキー。
  159 +
  160 +### `BAIDU_URL` (オプション)
  161 +
  162 +Baidu API の URL。
  163 +
  164 +### `BYTEDANCE_API_KEY` (オプション)
  165 +
  166 +ByteDance API キー。
  167 +
  168 +### `BYTEDANCE_URL` (オプション)
  169 +
  170 +ByteDance API の URL。
  171 +
  172 +### `ALIBABA_API_KEY` (オプション)
  173 +
  174 +アリババ(千问)API キー。
  175 +
  176 +### `ALIBABA_URL` (オプション)
  177 +
  178 +アリババ(千问)API の URL。
  179 +
  180 +### `HIDE_USER_API_KEY` (オプション)
  181 +
  182 +ユーザーが API キーを入力できないようにしたい場合は、この環境変数を 1 に設定します。
  183 +
  184 +### `DISABLE_GPT4` (オプション)
  185 +
  186 +ユーザーが GPT-4 を使用できないようにしたい場合は、この環境変数を 1 に設定します。
  187 +
  188 +### `ENABLE_BALANCE_QUERY` (オプション)
  189 +
  190 +バランスクエリ機能を有効にしたい場合は、この環境変数を 1 に設定します。
  191 +
  192 +### `DISABLE_FAST_LINK` (オプション)
  193 +
  194 +リンクからのプリセット設定解析を無効にしたい場合は、この環境変数を 1 に設定します。
  195 +
  196 +### `WHITE_WEBDAV_ENDPOINTS` (オプション)
  197 +
  198 +アクセス許可を与える WebDAV サービスのアドレスを追加したい場合、このオプションを使用します。フォーマット要件:
  199 +- 各アドレスは完全なエンドポイントでなければなりません。
  200 +> `https://xxxx/xxx`
  201 +- 複数のアドレスは `,` で接続します。
  202 +
  203 +### `CUSTOM_MODELS` (オプション)
  204 +
  205 +> 例:`+qwen-7b-chat,+glm-6b,-gpt-3.5-turbo,gpt-4-1106-preview=gpt-4-turbo` は `qwen-7b-chat` と `glm-6b` をモデルリストに追加し、`gpt-3.5-turbo` を削除し、`gpt-4-1106-preview` のモデル名を `gpt-4-turbo` として表示します。
  206 +> すべてのモデルを無効にし、特定のモデルを有効にしたい場合は、`-all,+gpt-3.5-turbo` を使用します。これは `gpt-3.5-turbo` のみを有効にすることを意味します。
  207 +
  208 +モデルリストを管理します。`+` でモデルを追加し、`-` でモデルを非表示にし、`モデル名=表示名` でモデルの表示名をカスタマイズし、カンマで区切ります。
  209 +
  210 +Azure モードでは、`modelName@Azure=deploymentName` 形式でモデル名とデプロイ名(deploy-name)を設定できます。
  211 +> 例:`+gpt-3.5-turbo@Azure=gpt35` この設定でモデルリストに `gpt35(Azure)` のオプションが表示されます。
  212 +
  213 +ByteDance モードでは、`modelName@bytedance=deploymentName` 形式でモデル名とデプロイ名(deploy-name)を設定できます。
  214 +> 例: `+Doubao-lite-4k@bytedance=ep-xxxxx-xxx` この設定でモデルリストに `Doubao-lite-4k(ByteDance)` のオプションが表示されます。
  215 +
  216 +### `DEFAULT_MODEL` (オプション)
  217 +
  218 +デフォルトのモデルを変更します。
  219 +
  220 +### `VISION_MODELS` (オプション)
  221 +
  222 +> デフォルト:空
  223 +> 例:`gpt-4-vision,claude-3-opus,my-custom-model` は、これらのモデルにビジョン機能を追加します。これはデフォルトのパターンマッチング("vision"、"claude-3"、"gemini-1.5"などのキーワードを含むモデルを検出)に加えて適用されます。
  224 +
  225 +デフォルトのパターンマッチングに加えて、追加のモデルにビジョン機能を付与します。複数のモデルはカンマで区切ります。
  226 +
  227 +### `DEFAULT_INPUT_TEMPLATE` (オプション)
  228 +
  229 +『設定』の『ユーザー入力前処理』の初期設定に使用するテンプレートをカスタマイズします。
  230 +
  231 +
  232 +## 開発
  233 +
  234 +下のボタンをクリックして二次開発を開始してください:
  235 +
  236 +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web)
  237 +
  238 +コードを書く前に、プロジェクトのルートディレクトリに `.env.local` ファイルを新規作成し、環境変数を記入します:
  239 +
  240 +```
  241 +OPENAI_API_KEY=<your api key here>
  242 +```
  243 +
  244 +
  245 +### ローカル開発
  246 +
  247 +1. Node.js 18 と Yarn をインストールします。具体的な方法は ChatGPT にお尋ねください。
  248 +2. `yarn install && yarn dev` を実行します。⚠️ 注意:このコマンドはローカル開発用であり、デプロイには使用しないでください。
  249 +3. ローカルでデプロイしたい場合は、`yarn install && yarn build && yarn start` コマンドを使用してください。プロセスを守るために pm2 を使用することもできます。詳細は ChatGPT にお尋ねください。
  250 +
  251 +
  252 +## デプロイ
  253 +
  254 +### コンテナデプロイ(推奨)
  255 +
  256 +> Docker バージョンは 20 以上が必要です。それ以下だとイメージが見つからないというエラーが出ます。
  257 +
  258 +> ⚠️ 注意:Docker バージョンは最新バージョンより 1~2 日遅れることが多いため、デプロイ後に「更新があります」の通知が出続けることがありますが、正常です。
  259 +
  260 +```shell
  261 +docker pull yidadaa/chatgpt-next-web
  262 +
  263 +docker run -d -p 3000:3000 \
  264 + -e OPENAI_API_KEY=sk-xxxx \
  265 + -e CODE=ページアクセスパスワード \
  266 + yidadaa/chatgpt-next-web
  267 +```
  268 +
  269 +プロキシを指定することもできます:
  270 +
  271 +```shell
  272 +docker run -d -p 3000:3000 \
  273 + -e OPENAI_API_KEY=sk-xxxx \
  274 + -e CODE=ページアクセスパスワード \
  275 + --net=host \
  276 + -e PROXY_URL=http://127.0.0.1:7890 \
  277 + yidadaa/chatgpt-next-web
  278 +```
  279 +
  280 +ローカルプロキシがアカウントとパスワードを必要とする場合は、以下を使用できます:
  281 +
  282 +```shell
  283 +-e PROXY_URL="http://127.0.0.1:7890 user password"
  284 +```
  285 +
  286 +他の環境変数を指定する必要がある場合は、上記のコマンドに `-e 環境変数=環境変数値` を追加して指定してください。
  287 +
  288 +
  289 +### ローカルデプロイ
  290 +
  291 +コンソールで以下のコマンドを実行します:
  292 +
  293 +```shell
  294 +bash <(curl -s https://raw.githubusercontent.com/Yidadaa/ChatGPT-Next-Web/main/scripts/setup.sh)
  295 +```
  296 +
  297 +⚠️ 注意:インストール中に問題が発生した場合は、Docker を使用してデプロイしてください。
  298 +
  299 +
  300 +## 謝辞
  301 +
  302 +### 寄付者
  303 +
  304 +> 英語版をご覧ください。
  305 +
  306 +### 貢献者
  307 +
  308 +[プロジェクトの貢献者リストはこちら](https://github.com/Yidadaa/ChatGPT-Next-Web/graphs/contributors)
  309 +
  310 +### 関連プロジェクト
  311 +
  312 +- [one-api](https://github.com/songquanpeng/one-api): 一つのプラットフォームで大規模モデルのクォータ管理を提供し、市場に出回っているすべての主要な大規模言語モデルをサポートします。
  313 +
  314 +
  315 +## オープンソースライセンス
  316 +
  317 +[MIT](https://opensource.org/license/mit/)
  1 +import { ApiPath } from "@/app/constant";
  2 +import { NextRequest } from "next/server";
  3 +import { handle as openaiHandler } from "../../openai";
  4 +import { handle as azureHandler } from "../../azure";
  5 +import { handle as googleHandler } from "../../google";
  6 +import { handle as anthropicHandler } from "../../anthropic";
  7 +import { handle as baiduHandler } from "../../baidu";
  8 +import { handle as bytedanceHandler } from "../../bytedance";
  9 +import { handle as alibabaHandler } from "../../alibaba";
  10 +import { handle as moonshotHandler } from "../../moonshot";
  11 +import { handle as stabilityHandler } from "../../stability";
  12 +import { handle as iflytekHandler } from "../../iflytek";
  13 +import { handle as deepseekHandler } from "../../deepseek";
  14 +import { handle as siliconflowHandler } from "../../siliconflow";
  15 +import { handle as xaiHandler } from "../../xai";
  16 +import { handle as chatglmHandler } from "../../glm";
  17 +import { handle as proxyHandler } from "../../proxy";
  18 +//20250321 新增佐糖API
  19 +import {handle as zuotangHandler} from "../../zuotang";
  20 +
  21 +async function handle(
  22 + req: NextRequest,
  23 + { params }: { params: { provider: string; path: string[] } },
  24 +) {
  25 + const apiPath = `/api/${params.provider}`;
  26 + console.log(`[${params.provider} Route] params `, params);
  27 + switch (apiPath) {
  28 + case ApiPath.Azure:
  29 + return azureHandler(req, { params });
  30 + case ApiPath.Google:
  31 + return googleHandler(req, { params });
  32 + case ApiPath.Anthropic:
  33 + return anthropicHandler(req, { params });
  34 + case ApiPath.Baidu:
  35 + return baiduHandler(req, { params });
  36 + case ApiPath.ByteDance:
  37 + return bytedanceHandler(req, { params });
  38 + case ApiPath.Alibaba:
  39 + return alibabaHandler(req, { params });
  40 + // case ApiPath.Tencent: using "/api/tencent"
  41 + case ApiPath.Moonshot:
  42 + return moonshotHandler(req, { params });
  43 + case ApiPath.Stability:
  44 + return stabilityHandler(req, { params });
  45 + case ApiPath.Iflytek:
  46 + return iflytekHandler(req, { params });
  47 + case ApiPath.DeepSeek:
  48 + return deepseekHandler(req, { params });
  49 + case ApiPath.XAI:
  50 + return xaiHandler(req, { params });
  51 + case ApiPath.ChatGLM:
  52 + return chatglmHandler(req, { params });
  53 + case ApiPath.SiliconFlow:
  54 + return siliconflowHandler(req, { params });
  55 + case ApiPath.OpenAI:
  56 + return openaiHandler(req, { params });
  57 + case ApiPath.ZuoTang:
  58 + return zuotangHandler(req,{ params })
  59 + default:
  60 + return proxyHandler(req, { params });
  61 + }
  62 +}
  63 +
  64 +export const GET = handle;
  65 +export const POST = handle;
  66 +
  67 +export const runtime = "edge";
  68 +export const preferredRegion = [
  69 + "arn1",
  70 + "bom1",
  71 + "cdg1",
  72 + "cle1",
  73 + "cpt1",
  74 + "dub1",
  75 + "fra1",
  76 + "gru1",
  77 + "hnd1",
  78 + "iad1",
  79 + "icn1",
  80 + "kix1",
  81 + "lhr1",
  82 + "pdx1",
  83 + "sfo1",
  84 + "sin1",
  85 + "syd1",
  86 +];
  1 +import { getServerSideConfig } from "@/app/config/server";
  2 +import {
  3 + ALIBABA_BASE_URL,
  4 + ApiPath,
  5 + ModelProvider,
  6 + ServiceProvider,
  7 +} from "@/app/constant";
  8 +import { prettyObject } from "@/app/utils/format";
  9 +import { NextRequest, NextResponse } from "next/server";
  10 +import { auth } from "@/app/api/auth";
  11 +import { isModelNotavailableInServer } from "@/app/utils/model";
  12 +
  13 +const serverConfig = getServerSideConfig();
  14 +
  15 +export async function handle(
  16 + req: NextRequest,
  17 + { params }: { params: { path: string[] } },
  18 +) {
  19 + console.log("[Alibaba Route] params ", params);
  20 +
  21 + if (req.method === "OPTIONS") {
  22 + return NextResponse.json({ body: "OK" }, { status: 200 });
  23 + }
  24 +
  25 + const authResult = auth(req, ModelProvider.Qwen);
  26 + if (authResult.error) {
  27 + return NextResponse.json(authResult, {
  28 + status: 401,
  29 + });
  30 + }
  31 +
  32 + try {
  33 + const response = await request(req);
  34 + return response;
  35 + } catch (e) {
  36 + console.error("[Alibaba] ", e);
  37 + return NextResponse.json(prettyObject(e));
  38 + }
  39 +}
  40 +
  41 +async function request(req: NextRequest) {
  42 + const controller = new AbortController();
  43 +
  44 + // alibaba use base url or just remove the path
  45 + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Alibaba, "");
  46 +
  47 + let baseUrl = serverConfig.alibabaUrl || ALIBABA_BASE_URL;
  48 +
  49 + if (!baseUrl.startsWith("http")) {
  50 + baseUrl = `https://${baseUrl}`;
  51 + }
  52 +
  53 + if (baseUrl.endsWith("/")) {
  54 + baseUrl = baseUrl.slice(0, -1);
  55 + }
  56 +
  57 + console.log("[Proxy] ", path);
  58 + console.log("[Base Url]", baseUrl);
  59 +
  60 + const timeoutId = setTimeout(
  61 + () => {
  62 + controller.abort();
  63 + },
  64 + 10 * 60 * 1000,
  65 + );
  66 +
  67 + const fetchUrl = `${baseUrl}${path}`;
  68 + const fetchOptions: RequestInit = {
  69 + headers: {
  70 + "Content-Type": "application/json",
  71 + Authorization: req.headers.get("Authorization") ?? "",
  72 + "X-DashScope-SSE": req.headers.get("X-DashScope-SSE") ?? "disable",
  73 + },
  74 + method: req.method,
  75 + body: req.body,
  76 + redirect: "manual",
  77 + // @ts-ignore
  78 + duplex: "half",
  79 + signal: controller.signal,
  80 + };
  81 +
  82 + // #1815 try to refuse some request to some models
  83 + if (serverConfig.customModels && req.body) {
  84 + try {
  85 + const clonedBody = await req.text();
  86 + fetchOptions.body = clonedBody;
  87 +
  88 + const jsonBody = JSON.parse(clonedBody) as { model?: string };
  89 +
  90 + // not undefined and is false
  91 + if (
  92 + isModelNotavailableInServer(
  93 + serverConfig.customModels,
  94 + jsonBody?.model as string,
  95 + ServiceProvider.Alibaba as string,
  96 + )
  97 + ) {
  98 + return NextResponse.json(
  99 + {
  100 + error: true,
  101 + message: `you are not allowed to use ${jsonBody?.model} model`,
  102 + },
  103 + {
  104 + status: 403,
  105 + },
  106 + );
  107 + }
  108 + } catch (e) {
  109 + console.error(`[Alibaba] filter`, e);
  110 + }
  111 + }
  112 + try {
  113 + const res = await fetch(fetchUrl, fetchOptions);
  114 +
  115 + // to prevent browser prompt for credentials
  116 + const newHeaders = new Headers(res.headers);
  117 + newHeaders.delete("www-authenticate");
  118 + // to disable nginx buffering
  119 + newHeaders.set("X-Accel-Buffering", "no");
  120 +
  121 + return new Response(res.body, {
  122 + status: res.status,
  123 + statusText: res.statusText,
  124 + headers: newHeaders,
  125 + });
  126 + } finally {
  127 + clearTimeout(timeoutId);
  128 + }
  129 +}
  1 +import { getServerSideConfig } from "@/app/config/server";
  2 +import {
  3 + ANTHROPIC_BASE_URL,
  4 + Anthropic,
  5 + ApiPath,
  6 + ServiceProvider,
  7 + ModelProvider,
  8 +} from "@/app/constant";
  9 +import { prettyObject } from "@/app/utils/format";
  10 +import { NextRequest, NextResponse } from "next/server";
  11 +import { auth } from "./auth";
  12 +import { isModelNotavailableInServer } from "@/app/utils/model";
  13 +import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  14 +
  15 +const ALLOWD_PATH = new Set([Anthropic.ChatPath, Anthropic.ChatPath1]);
  16 +
  17 +export async function handle(
  18 + req: NextRequest,
  19 + { params }: { params: { path: string[] } },
  20 +) {
  21 + console.log("[Anthropic Route] params ", params);
  22 +
  23 + if (req.method === "OPTIONS") {
  24 + return NextResponse.json({ body: "OK" }, { status: 200 });
  25 + }
  26 +
  27 + const subpath = params.path.join("/");
  28 +
  29 + if (!ALLOWD_PATH.has(subpath)) {
  30 + console.log("[Anthropic Route] forbidden path ", subpath);
  31 + return NextResponse.json(
  32 + {
  33 + error: true,
  34 + msg: "you are not allowed to request " + subpath,
  35 + },
  36 + {
  37 + status: 403,
  38 + },
  39 + );
  40 + }
  41 +
  42 + const authResult = auth(req, ModelProvider.Claude);
  43 + if (authResult.error) {
  44 + return NextResponse.json(authResult, {
  45 + status: 401,
  46 + });
  47 + }
  48 +
  49 + try {
  50 + const response = await request(req);
  51 + return response;
  52 + } catch (e) {
  53 + console.error("[Anthropic] ", e);
  54 + return NextResponse.json(prettyObject(e));
  55 + }
  56 +}
  57 +
  58 +const serverConfig = getServerSideConfig();
  59 +
  60 +async function request(req: NextRequest) {
  61 + const controller = new AbortController();
  62 +
  63 + let authHeaderName = "x-api-key";
  64 + let authValue =
  65 + req.headers.get(authHeaderName) ||
  66 + req.headers.get("Authorization")?.replaceAll("Bearer ", "").trim() ||
  67 + serverConfig.anthropicApiKey ||
  68 + "";
  69 +
  70 + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Anthropic, "");
  71 +
  72 + let baseUrl =
  73 + serverConfig.anthropicUrl || serverConfig.baseUrl || ANTHROPIC_BASE_URL;
  74 +
  75 + if (!baseUrl.startsWith("http")) {
  76 + baseUrl = `https://${baseUrl}`;
  77 + }
  78 +
  79 + if (baseUrl.endsWith("/")) {
  80 + baseUrl = baseUrl.slice(0, -1);
  81 + }
  82 +
  83 + console.log("[Proxy] ", path);
  84 + console.log("[Base Url]", baseUrl);
  85 +
  86 + const timeoutId = setTimeout(
  87 + () => {
  88 + controller.abort();
  89 + },
  90 + 10 * 60 * 1000,
  91 + );
  92 +
  93 + // try rebuild url, when using cloudflare ai gateway in server
  94 + const fetchUrl = cloudflareAIGatewayUrl(`${baseUrl}${path}`);
  95 +
  96 + const fetchOptions: RequestInit = {
  97 + headers: {
  98 + "Content-Type": "application/json",
  99 + "Cache-Control": "no-store",
  100 + "anthropic-dangerous-direct-browser-access": "true",
  101 + [authHeaderName]: authValue,
  102 + "anthropic-version":
  103 + req.headers.get("anthropic-version") ||
  104 + serverConfig.anthropicApiVersion ||
  105 + Anthropic.Vision,
  106 + },
  107 + method: req.method,
  108 + body: req.body,
  109 + redirect: "manual",
  110 + // @ts-ignore
  111 + duplex: "half",
  112 + signal: controller.signal,
  113 + };
  114 +
  115 + // #1815 try to refuse some request to some models
  116 + if (serverConfig.customModels && req.body) {
  117 + try {
  118 + const clonedBody = await req.text();
  119 + fetchOptions.body = clonedBody;
  120 +
  121 + const jsonBody = JSON.parse(clonedBody) as { model?: string };
  122 +
  123 + // not undefined and is false
  124 + if (
  125 + isModelNotavailableInServer(
  126 + serverConfig.customModels,
  127 + jsonBody?.model as string,
  128 + ServiceProvider.Anthropic as string,
  129 + )
  130 + ) {
  131 + return NextResponse.json(
  132 + {
  133 + error: true,
  134 + message: `you are not allowed to use ${jsonBody?.model} model`,
  135 + },
  136 + {
  137 + status: 403,
  138 + },
  139 + );
  140 + }
  141 + } catch (e) {
  142 + console.error(`[Anthropic] filter`, e);
  143 + }
  144 + }
  145 + // console.log("[Anthropic request]", fetchOptions.headers, req.method);
  146 + try {
  147 + const res = await fetch(fetchUrl, fetchOptions);
  148 +
  149 + // console.log(
  150 + // "[Anthropic response]",
  151 + // res.status,
  152 + // " ",
  153 + // res.headers,
  154 + // res.url,
  155 + // );
  156 + // to prevent browser prompt for credentials
  157 + const newHeaders = new Headers(res.headers);
  158 + newHeaders.delete("www-authenticate");
  159 + // to disable nginx buffering
  160 + newHeaders.set("X-Accel-Buffering", "no");
  161 +
  162 + return new Response(res.body, {
  163 + status: res.status,
  164 + statusText: res.statusText,
  165 + headers: newHeaders,
  166 + });
  167 + } finally {
  168 + clearTimeout(timeoutId);
  169 + }
  170 +}
  1 +import md5 from "spark-md5";
  2 +import { NextRequest, NextResponse } from "next/server";
  3 +import { getServerSideConfig } from "@/app/config/server";
  4 +
  5 +async function handle(req: NextRequest, res: NextResponse) {
  6 + const serverConfig = getServerSideConfig();
  7 + const storeUrl = () =>
  8 + `https://api.cloudflare.com/client/v4/accounts/${serverConfig.cloudflareAccountId}/storage/kv/namespaces/${serverConfig.cloudflareKVNamespaceId}`;
  9 + const storeHeaders = () => ({
  10 + Authorization: `Bearer ${serverConfig.cloudflareKVApiKey}`,
  11 + });
  12 + if (req.method === "POST") {
  13 + const clonedBody = await req.text();
  14 + const hashedCode = md5.hash(clonedBody).trim();
  15 + const body: {
  16 + key: string;
  17 + value: string;
  18 + expiration_ttl?: number;
  19 + } = {
  20 + key: hashedCode,
  21 + value: clonedBody,
  22 + };
  23 + try {
  24 + const ttl = parseInt(serverConfig.cloudflareKVTTL as string);
  25 + if (ttl > 60) {
  26 + body["expiration_ttl"] = ttl;
  27 + }
  28 + } catch (e) {
  29 + console.error(e);
  30 + }
  31 + const res = await fetch(`${storeUrl()}/bulk`, {
  32 + headers: {
  33 + ...storeHeaders(),
  34 + "Content-Type": "application/json",
  35 + },
  36 + method: "PUT",
  37 + body: JSON.stringify([body]),
  38 + });
  39 + const result = await res.json();
  40 + console.log("save data", result);
  41 + if (result?.success) {
  42 + return NextResponse.json(
  43 + { code: 0, id: hashedCode, result },
  44 + { status: res.status },
  45 + );
  46 + }
  47 + return NextResponse.json(
  48 + { error: true, msg: "Save data error" },
  49 + { status: 400 },
  50 + );
  51 + }
  52 + if (req.method === "GET") {
  53 + const id = req?.nextUrl?.searchParams?.get("id");
  54 + const res = await fetch(`${storeUrl()}/values/${id}`, {
  55 + headers: storeHeaders(),
  56 + method: "GET",
  57 + });
  58 + return new Response(res.body, {
  59 + status: res.status,
  60 + statusText: res.statusText,
  61 + headers: res.headers,
  62 + });
  63 + }
  64 + return NextResponse.json(
  65 + { error: true, msg: "Invalid request" },
  66 + { status: 400 },
  67 + );
  68 +}
  69 +
  70 +export const POST = handle;
  71 +export const GET = handle;
  72 +
  73 +export const runtime = "edge";
  1 +import { NextRequest } from "next/server";
  2 +import { getServerSideConfig } from "../config/server";
  3 +import md5 from "spark-md5";
  4 +import { ACCESS_CODE_PREFIX, ModelProvider } from "../constant";
  5 +
  6 +function getIP(req: NextRequest) {
  7 + let ip = req.ip ?? req.headers.get("x-real-ip");
  8 + const forwardedFor = req.headers.get("x-forwarded-for");
  9 +
  10 + if (!ip && forwardedFor) {
  11 + ip = forwardedFor.split(",").at(0) ?? "";
  12 + }
  13 +
  14 + return ip;
  15 +}
  16 +
  17 +function parseApiKey(bearToken: string) {
  18 + const token = bearToken.trim().replaceAll("Bearer ", "").trim();
  19 + const isApiKey = !token.startsWith(ACCESS_CODE_PREFIX);
  20 +
  21 + return {
  22 + accessCode: isApiKey ? "" : token.slice(ACCESS_CODE_PREFIX.length),
  23 + apiKey: isApiKey ? token : "",
  24 + };
  25 +}
  26 +
  27 +export function auth(req: NextRequest, modelProvider: ModelProvider) {
  28 + const authToken = req.headers.get("Authorization") ?? "";
  29 + // check if it is openai api key or user token
  30 + const { accessCode, apiKey } = parseApiKey(authToken);
  31 +
  32 + const hashedCode = md5.hash(accessCode ?? "").trim();
  33 +
  34 + const serverConfig = getServerSideConfig();
  35 + console.log("[Auth] allowed hashed codes: ", [...serverConfig.codes]);
  36 + console.log("[Auth] got access code:", accessCode);
  37 + console.log("[Auth] hashed access code:", hashedCode);
  38 + console.log("[User IP] ", getIP(req));
  39 + console.log("[Time] ", new Date().toLocaleString());
  40 +
  41 + if (serverConfig.needCode && !serverConfig.codes.has(hashedCode) && !apiKey) {
  42 + return {
  43 + error: true,
  44 + msg: !accessCode ? "empty access code" : "wrong access code",
  45 + };
  46 + }
  47 +
  48 + if (serverConfig.hideUserApiKey && !!apiKey) {
  49 + return {
  50 + error: true,
  51 + msg: "you are not allowed to access with your own api key",
  52 + };
  53 + }
  54 +
  55 + // if user does not provide an api key, inject system api key
  56 + if (!apiKey) {
  57 + const serverConfig = getServerSideConfig();
  58 +
  59 + // const systemApiKey =
  60 + // modelProvider === ModelProvider.GeminiPro
  61 + // ? serverConfig.googleApiKey
  62 + // : serverConfig.isAzure
  63 + // ? serverConfig.azureApiKey
  64 + // : serverConfig.apiKey;
  65 +
  66 + let systemApiKey: string | undefined;
  67 +
  68 + switch (modelProvider) {
  69 + case ModelProvider.Stability:
  70 + systemApiKey = serverConfig.stabilityApiKey;
  71 + break;
  72 + case ModelProvider.GeminiPro:
  73 + systemApiKey = serverConfig.googleApiKey;
  74 + break;
  75 + case ModelProvider.Claude:
  76 + systemApiKey = serverConfig.anthropicApiKey;
  77 + break;
  78 + case ModelProvider.Doubao:
  79 + systemApiKey = serverConfig.bytedanceApiKey;
  80 + break;
  81 + case ModelProvider.Ernie:
  82 + systemApiKey = serverConfig.baiduApiKey;
  83 + break;
  84 + case ModelProvider.Qwen:
  85 + systemApiKey = serverConfig.alibabaApiKey;
  86 + break;
  87 + case ModelProvider.Moonshot:
  88 + systemApiKey = serverConfig.moonshotApiKey;
  89 + break;
  90 + case ModelProvider.Iflytek:
  91 + systemApiKey =
  92 + serverConfig.iflytekApiKey + ":" + serverConfig.iflytekApiSecret;
  93 + break;
  94 + case ModelProvider.DeepSeek:
  95 + systemApiKey = serverConfig.deepseekApiKey;
  96 + break;
  97 + case ModelProvider.XAI:
  98 + systemApiKey = serverConfig.xaiApiKey;
  99 + break;
  100 + case ModelProvider.ChatGLM:
  101 + systemApiKey = serverConfig.chatglmApiKey;
  102 + break;
  103 + case ModelProvider.SiliconFlow:
  104 + systemApiKey = serverConfig.siliconFlowApiKey;
  105 + break;
  106 + case ModelProvider.GPT:
  107 + default:
  108 + if (req.nextUrl.pathname.includes("azure/deployments")) {
  109 + systemApiKey = serverConfig.azureApiKey;
  110 + } else {
  111 + systemApiKey = serverConfig.apiKey;
  112 + }
  113 + }
  114 +
  115 + if (systemApiKey) {
  116 + console.log("[Auth] use system api key");
  117 + req.headers.set("Authorization", `Bearer ${systemApiKey}`);
  118 + } else {
  119 + console.log("[Auth] admin did not provide an api key");
  120 + }
  121 + } else {
  122 + console.log("[Auth] use user api key");
  123 + }
  124 +
  125 + return {
  126 + error: false,
  127 + };
  128 +}
  1 +import { ModelProvider } from "@/app/constant";
  2 +import { prettyObject } from "@/app/utils/format";
  3 +import { NextRequest, NextResponse } from "next/server";
  4 +import { auth } from "./auth";
  5 +import { requestOpenai } from "./common";
  6 +
  7 +export async function handle(
  8 + req: NextRequest,
  9 + { params }: { params: { path: string[] } },
  10 +) {
  11 + console.log("[Azure Route] params ", params);
  12 +
  13 + if (req.method === "OPTIONS") {
  14 + return NextResponse.json({ body: "OK" }, { status: 200 });
  15 + }
  16 +
  17 + const subpath = params.path.join("/");
  18 +
  19 + const authResult = auth(req, ModelProvider.GPT);
  20 + if (authResult.error) {
  21 + return NextResponse.json(authResult, {
  22 + status: 401,
  23 + });
  24 + }
  25 +
  26 + try {
  27 + return await requestOpenai(req);
  28 + } catch (e) {
  29 + console.error("[Azure] ", e);
  30 + return NextResponse.json(prettyObject(e));
  31 + }
  32 +}
  1 +import { getServerSideConfig } from "@/app/config/server";
  2 +import {
  3 + BAIDU_BASE_URL,
  4 + ApiPath,
  5 + ModelProvider,
  6 + ServiceProvider,
  7 +} from "@/app/constant";
  8 +import { prettyObject } from "@/app/utils/format";
  9 +import { NextRequest, NextResponse } from "next/server";
  10 +import { auth } from "@/app/api/auth";
  11 +import { isModelNotavailableInServer } from "@/app/utils/model";
  12 +import { getAccessToken } from "@/app/utils/baidu";
  13 +
  14 +const serverConfig = getServerSideConfig();
  15 +
  16 +export async function handle(
  17 + req: NextRequest,
  18 + { params }: { params: { path: string[] } },
  19 +) {
  20 + console.log("[Baidu Route] params ", params);
  21 +
  22 + if (req.method === "OPTIONS") {
  23 + return NextResponse.json({ body: "OK" }, { status: 200 });
  24 + }
  25 +
  26 + const authResult = auth(req, ModelProvider.Ernie);
  27 + if (authResult.error) {
  28 + return NextResponse.json(authResult, {
  29 + status: 401,
  30 + });
  31 + }
  32 +
  33 + if (!serverConfig.baiduApiKey || !serverConfig.baiduSecretKey) {
  34 + return NextResponse.json(
  35 + {
  36 + error: true,
  37 + message: `missing BAIDU_API_KEY or BAIDU_SECRET_KEY in server env vars`,
  38 + },
  39 + {
  40 + status: 401,
  41 + },
  42 + );
  43 + }
  44 +
  45 + try {
  46 + const response = await request(req);
  47 + return response;
  48 + } catch (e) {
  49 + console.error("[Baidu] ", e);
  50 + return NextResponse.json(prettyObject(e));
  51 + }
  52 +}
  53 +
  54 +async function request(req: NextRequest) {
  55 + const controller = new AbortController();
  56 +
  57 + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Baidu, "");
  58 +
  59 + let baseUrl = serverConfig.baiduUrl || BAIDU_BASE_URL;
  60 +
  61 + if (!baseUrl.startsWith("http")) {
  62 + baseUrl = `https://${baseUrl}`;
  63 + }
  64 +
  65 + if (baseUrl.endsWith("/")) {
  66 + baseUrl = baseUrl.slice(0, -1);
  67 + }
  68 +
  69 + console.log("[Proxy] ", path);
  70 + console.log("[Base Url]", baseUrl);
  71 +
  72 + const timeoutId = setTimeout(
  73 + () => {
  74 + controller.abort();
  75 + },
  76 + 10 * 60 * 1000,
  77 + );
  78 +
  79 + const { access_token } = await getAccessToken(
  80 + serverConfig.baiduApiKey as string,
  81 + serverConfig.baiduSecretKey as string,
  82 + );
  83 + const fetchUrl = `${baseUrl}${path}?access_token=${access_token}`;
  84 +
  85 + const fetchOptions: RequestInit = {
  86 + headers: {
  87 + "Content-Type": "application/json",
  88 + },
  89 + method: req.method,
  90 + body: req.body,
  91 + redirect: "manual",
  92 + // @ts-ignore
  93 + duplex: "half",
  94 + signal: controller.signal,
  95 + };
  96 +
  97 + // #1815 try to refuse some request to some models
  98 + if (serverConfig.customModels && req.body) {
  99 + try {
  100 + const clonedBody = await req.text();
  101 + fetchOptions.body = clonedBody;
  102 +
  103 + const jsonBody = JSON.parse(clonedBody) as { model?: string };
  104 +
  105 + // not undefined and is false
  106 + if (
  107 + isModelNotavailableInServer(
  108 + serverConfig.customModels,
  109 + jsonBody?.model as string,
  110 + ServiceProvider.Baidu as string,
  111 + )
  112 + ) {
  113 + return NextResponse.json(
  114 + {
  115 + error: true,
  116 + message: `you are not allowed to use ${jsonBody?.model} model`,
  117 + },
  118 + {
  119 + status: 403,
  120 + },
  121 + );
  122 + }
  123 + } catch (e) {
  124 + console.error(`[Baidu] filter`, e);
  125 + }
  126 + }
  127 + try {
  128 + const res = await fetch(fetchUrl, fetchOptions);
  129 +
  130 + // to prevent browser prompt for credentials
  131 + const newHeaders = new Headers(res.headers);
  132 + newHeaders.delete("www-authenticate");
  133 + // to disable nginx buffering
  134 + newHeaders.set("X-Accel-Buffering", "no");
  135 +
  136 + return new Response(res.body, {
  137 + status: res.status,
  138 + statusText: res.statusText,
  139 + headers: newHeaders,
  140 + });
  141 + } finally {
  142 + clearTimeout(timeoutId);
  143 + }
  144 +}
  1 +import { getServerSideConfig } from "@/app/config/server";
  2 +import {
  3 + BYTEDANCE_BASE_URL,
  4 + ApiPath,
  5 + ModelProvider,
  6 + ServiceProvider,
  7 +} from "@/app/constant";
  8 +import { prettyObject } from "@/app/utils/format";
  9 +import { NextRequest, NextResponse } from "next/server";
  10 +import { auth } from "@/app/api/auth";
  11 +import { isModelNotavailableInServer } from "@/app/utils/model";
  12 +
  13 +const serverConfig = getServerSideConfig();
  14 +
  15 +export async function handle(
  16 + req: NextRequest,
  17 + { params }: { params: { path: string[] } },
  18 +) {
  19 + console.log("[ByteDance Route] params ", params);
  20 +
  21 + if (req.method === "OPTIONS") {
  22 + return NextResponse.json({ body: "OK" }, { status: 200 });
  23 + }
  24 +
  25 + const authResult = auth(req, ModelProvider.Doubao);
  26 + if (authResult.error) {
  27 + return NextResponse.json(authResult, {
  28 + status: 401,
  29 + });
  30 + }
  31 +
  32 + try {
  33 + const response = await request(req);
  34 + return response;
  35 + } catch (e) {
  36 + console.error("[ByteDance] ", e);
  37 + return NextResponse.json(prettyObject(e));
  38 + }
  39 +}
  40 +
  41 +async function request(req: NextRequest) {
  42 + const controller = new AbortController();
  43 +
  44 + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.ByteDance, "");
  45 +
  46 + let baseUrl = serverConfig.bytedanceUrl || BYTEDANCE_BASE_URL;
  47 +
  48 + if (!baseUrl.startsWith("http")) {
  49 + baseUrl = `https://${baseUrl}`;
  50 + }
  51 +
  52 + if (baseUrl.endsWith("/")) {
  53 + baseUrl = baseUrl.slice(0, -1);
  54 + }
  55 +
  56 + console.log("[Proxy] ", path);
  57 + console.log("[Base Url]", baseUrl);
  58 +
  59 + const timeoutId = setTimeout(
  60 + () => {
  61 + controller.abort();
  62 + },
  63 + 10 * 60 * 1000,
  64 + );
  65 +
  66 + const fetchUrl = `${baseUrl}${path}`;
  67 +
  68 + const fetchOptions: RequestInit = {
  69 + headers: {
  70 + "Content-Type": "application/json",
  71 + Authorization: req.headers.get("Authorization") ?? "",
  72 + },
  73 + method: req.method,
  74 + body: req.body,
  75 + redirect: "manual",
  76 + // @ts-ignore
  77 + duplex: "half",
  78 + signal: controller.signal,
  79 + };
  80 +
  81 + // #1815 try to refuse some request to some models
  82 + if (serverConfig.customModels && req.body) {
  83 + try {
  84 + const clonedBody = await req.text();
  85 + fetchOptions.body = clonedBody;
  86 +
  87 + const jsonBody = JSON.parse(clonedBody) as { model?: string };
  88 +
  89 + // not undefined and is false
  90 + if (
  91 + isModelNotavailableInServer(
  92 + serverConfig.customModels,
  93 + jsonBody?.model as string,
  94 + ServiceProvider.ByteDance as string,
  95 + )
  96 + ) {
  97 + return NextResponse.json(
  98 + {
  99 + error: true,
  100 + message: `you are not allowed to use ${jsonBody?.model} model`,
  101 + },
  102 + {
  103 + status: 403,
  104 + },
  105 + );
  106 + }
  107 + } catch (e) {
  108 + console.error(`[ByteDance] filter`, e);
  109 + }
  110 + }
  111 +
  112 + try {
  113 + const res = await fetch(fetchUrl, fetchOptions);
  114 +
  115 + // to prevent browser prompt for credentials
  116 + const newHeaders = new Headers(res.headers);
  117 + newHeaders.delete("www-authenticate");
  118 + // to disable nginx buffering
  119 + newHeaders.set("X-Accel-Buffering", "no");
  120 +
  121 + return new Response(res.body, {
  122 + status: res.status,
  123 + statusText: res.statusText,
  124 + headers: newHeaders,
  125 + });
  126 + } finally {
  127 + clearTimeout(timeoutId);
  128 + }
  129 +}
  1 +import { NextRequest, NextResponse } from "next/server";
  2 +import { getServerSideConfig } from "../config/server";
  3 +import { OPENAI_BASE_URL, ServiceProvider } from "../constant";
  4 +import { cloudflareAIGatewayUrl } from "../utils/cloudflare";
  5 +import { getModelProvider, isModelNotavailableInServer } from "../utils/model";
  6 +
  7 +const serverConfig = getServerSideConfig();
  8 +
  9 +export async function requestOpenai(req: NextRequest) {
  10 + const controller = new AbortController();
  11 +
  12 + const isAzure = req.nextUrl.pathname.includes("azure/deployments");
  13 +
  14 + var authValue,
  15 + authHeaderName = "";
  16 + if (isAzure) {
  17 + authValue =
  18 + req.headers
  19 + .get("Authorization")
  20 + ?.trim()
  21 + .replaceAll("Bearer ", "")
  22 + .trim() ?? "";
  23 +
  24 + authHeaderName = "api-key";
  25 + } else {
  26 + authValue = req.headers.get("Authorization") ?? "";
  27 + authHeaderName = "Authorization";
  28 + }
  29 +
  30 + let path = `${req.nextUrl.pathname}`.replaceAll("/api/openai/", "");
  31 +
  32 + let baseUrl =
  33 + (isAzure ? serverConfig.azureUrl : serverConfig.baseUrl) || OPENAI_BASE_URL;
  34 +
  35 + if (!baseUrl.startsWith("http")) {
  36 + baseUrl = `https://${baseUrl}`;
  37 + }
  38 +
  39 + if (baseUrl.endsWith("/")) {
  40 + baseUrl = baseUrl.slice(0, -1);
  41 + }
  42 +
  43 + console.log("[Proxy] ", path);
  44 + console.log("[Base Url]", baseUrl);
  45 +
  46 + const timeoutId = setTimeout(
  47 + () => {
  48 + controller.abort();
  49 + },
  50 + 10 * 60 * 1000,
  51 + );
  52 +
  53 + if (isAzure) {
  54 + const azureApiVersion =
  55 + req?.nextUrl?.searchParams?.get("api-version") ||
  56 + serverConfig.azureApiVersion;
  57 + baseUrl = baseUrl.split("/deployments").shift() as string;
  58 + path = `${req.nextUrl.pathname.replaceAll(
  59 + "/api/azure/",
  60 + "",
  61 + )}?api-version=${azureApiVersion}`;
  62 +
  63 + // Forward compatibility:
  64 + // if display_name(deployment_name) not set, and '{deploy-id}' in AZURE_URL
  65 + // then using default '{deploy-id}'
  66 + if (serverConfig.customModels && serverConfig.azureUrl) {
  67 + const modelName = path.split("/")[1];
  68 + let realDeployName = "";
  69 + serverConfig.customModels
  70 + .split(",")
  71 + .filter((v) => !!v && !v.startsWith("-") && v.includes(modelName))
  72 + .forEach((m) => {
  73 + const [fullName, displayName] = m.split("=");
  74 + const [_, providerName] = getModelProvider(fullName);
  75 + if (providerName === "azure" && !displayName) {
  76 + const [_, deployId] = (serverConfig?.azureUrl ?? "").split(
  77 + "deployments/",
  78 + );
  79 + if (deployId) {
  80 + realDeployName = deployId;
  81 + }
  82 + }
  83 + });
  84 + if (realDeployName) {
  85 + console.log("[Replace with DeployId", realDeployName);
  86 + path = path.replaceAll(modelName, realDeployName);
  87 + }
  88 + }
  89 + }
  90 +
  91 + const fetchUrl = cloudflareAIGatewayUrl(`${baseUrl}/${path}`);
  92 + console.log("fetchUrl", fetchUrl);
  93 + const fetchOptions: RequestInit = {
  94 + headers: {
  95 + "Content-Type": "application/json",
  96 + "Cache-Control": "no-store",
  97 + [authHeaderName]: authValue,
  98 + ...(serverConfig.openaiOrgId && {
  99 + "OpenAI-Organization": serverConfig.openaiOrgId,
  100 + }),
  101 + },
  102 + method: req.method,
  103 + body: req.body,
  104 + // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  105 + redirect: "manual",
  106 + // @ts-ignore
  107 + duplex: "half",
  108 + signal: controller.signal,
  109 + };
  110 +
  111 + // #1815 try to refuse gpt4 request
  112 + if (serverConfig.customModels && req.body) {
  113 + try {
  114 + const clonedBody = await req.text();
  115 + fetchOptions.body = clonedBody;
  116 +
  117 + const jsonBody = JSON.parse(clonedBody) as { model?: string };
  118 +
  119 + // not undefined and is false
  120 + if (
  121 + isModelNotavailableInServer(
  122 + serverConfig.customModels,
  123 + jsonBody?.model as string,
  124 + [
  125 + ServiceProvider.OpenAI,
  126 + ServiceProvider.Azure,
  127 + jsonBody?.model as string, // support provider-unspecified model
  128 + ],
  129 + )
  130 + ) {
  131 + return NextResponse.json(
  132 + {
  133 + error: true,
  134 + message: `you are not allowed to use ${jsonBody?.model} model`,
  135 + },
  136 + {
  137 + status: 403,
  138 + },
  139 + );
  140 + }
  141 + } catch (e) {
  142 + console.error("[OpenAI] gpt4 filter", e);
  143 + }
  144 + }
  145 +
  146 + try {
  147 + const res = await fetch(fetchUrl, fetchOptions);
  148 +
  149 + // Extract the OpenAI-Organization header from the response
  150 + const openaiOrganizationHeader = res.headers.get("OpenAI-Organization");
  151 +
  152 + // Check if serverConfig.openaiOrgId is defined and not an empty string
  153 + if (serverConfig.openaiOrgId && serverConfig.openaiOrgId.trim() !== "") {
  154 + // If openaiOrganizationHeader is present, log it; otherwise, log that the header is not present
  155 + console.log("[Org ID]", openaiOrganizationHeader);
  156 + } else {
  157 + console.log("[Org ID] is not set up.");
  158 + }
  159 +
  160 + // to prevent browser prompt for credentials
  161 + const newHeaders = new Headers(res.headers);
  162 + newHeaders.delete("www-authenticate");
  163 + // to disable nginx buffering
  164 + newHeaders.set("X-Accel-Buffering", "no");
  165 +
  166 + // Conditionally delete the OpenAI-Organization header from the response if [Org ID] is undefined or empty (not setup in ENV)
  167 + // Also, this is to prevent the header from being sent to the client
  168 + if (!serverConfig.openaiOrgId || serverConfig.openaiOrgId.trim() === "") {
  169 + newHeaders.delete("OpenAI-Organization");
  170 + }
  171 +
  172 + // The latest version of the OpenAI API forced the content-encoding to be "br" in json response
  173 + // So if the streaming is disabled, we need to remove the content-encoding header
  174 + // Because Vercel uses gzip to compress the response, if we don't remove the content-encoding header
  175 + // The browser will try to decode the response with brotli and fail
  176 + newHeaders.delete("content-encoding");
  177 +
  178 + return new Response(res.body, {
  179 + status: res.status,
  180 + statusText: res.statusText,
  181 + headers: newHeaders,
  182 + });
  183 + } finally {
  184 + clearTimeout(timeoutId);
  185 + }
  186 +}
  1 +import { NextResponse } from "next/server";
  2 +
  3 +import { getServerSideConfig } from "../../config/server";
  4 +
  5 +const serverConfig = getServerSideConfig();
  6 +
  7 +// Danger! Do not hard code any secret value here!
  8 +// 警告!不要在这里写入任何敏感信息!
  9 +const DANGER_CONFIG = {
  10 + needCode: serverConfig.needCode,
  11 + hideUserApiKey: serverConfig.hideUserApiKey,
  12 + disableGPT4: serverConfig.disableGPT4,
  13 + hideBalanceQuery: serverConfig.hideBalanceQuery,
  14 + disableFastLink: serverConfig.disableFastLink,
  15 + customModels: serverConfig.customModels,
  16 + defaultModel: serverConfig.defaultModel,
  17 + visionModels: serverConfig.visionModels,
  18 +};
  19 +
  20 +declare global {
  21 + type DangerConfig = typeof DANGER_CONFIG;
  22 +}
  23 +
  24 +async function handle() {
  25 + return NextResponse.json(DANGER_CONFIG);
  26 +}
  27 +
  28 +export const GET = handle;
  29 +export const POST = handle;
  30 +
  31 +export const runtime = "edge";
  1 +import { getServerSideConfig } from "@/app/config/server";
  2 +import {
  3 + DEEPSEEK_BASE_URL,
  4 + ApiPath,
  5 + ModelProvider,
  6 + ServiceProvider,
  7 +} from "@/app/constant";
  8 +import { prettyObject } from "@/app/utils/format";
  9 +import { NextRequest, NextResponse } from "next/server";
  10 +import { auth } from "@/app/api/auth";
  11 +import { isModelNotavailableInServer } from "@/app/utils/model";
  12 +
  13 +const serverConfig = getServerSideConfig();
  14 +
  15 +export async function handle(
  16 + req: NextRequest,
  17 + { params }: { params: { path: string[] } },
  18 +) {
  19 + console.log("[DeepSeek Route] params ", params);
  20 +
  21 + if (req.method === "OPTIONS") {
  22 + return NextResponse.json({ body: "OK" }, { status: 200 });
  23 + }
  24 +
  25 + const authResult = auth(req, ModelProvider.DeepSeek);
  26 + if (authResult.error) {
  27 + return NextResponse.json(authResult, {
  28 + status: 401,
  29 + });
  30 + }
  31 +
  32 + try {
  33 + const response = await request(req);
  34 + return response;
  35 + } catch (e) {
  36 + console.error("[DeepSeek] ", e);
  37 + return NextResponse.json(prettyObject(e));
  38 + }
  39 +}
  40 +
  41 +async function request(req: NextRequest) {
  42 + const controller = new AbortController();
  43 +
  44 + // alibaba use base url or just remove the path
  45 + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.DeepSeek, "");
  46 +
  47 + let baseUrl = serverConfig.deepseekUrl || DEEPSEEK_BASE_URL;
  48 +
  49 + if (!baseUrl.startsWith("http")) {
  50 + baseUrl = `https://${baseUrl}`;
  51 + }
  52 +
  53 + if (baseUrl.endsWith("/")) {
  54 + baseUrl = baseUrl.slice(0, -1);
  55 + }
  56 +
  57 + console.log("[Proxy] ", path);
  58 + console.log("[Base Url]", baseUrl);
  59 +
  60 + const timeoutId = setTimeout(
  61 + () => {
  62 + controller.abort();
  63 + },
  64 + 10 * 60 * 1000,
  65 + );
  66 +
  67 + const fetchUrl = `${baseUrl}${path}`;
  68 + const fetchOptions: RequestInit = {
  69 + headers: {
  70 + "Content-Type": "application/json",
  71 + Authorization: req.headers.get("Authorization") ?? "",
  72 + },
  73 + method: req.method,
  74 + body: req.body,
  75 + redirect: "manual",
  76 + // @ts-ignore
  77 + duplex: "half",
  78 + signal: controller.signal,
  79 + };
  80 +
  81 + // #1815 try to refuse some request to some models
  82 + if (serverConfig.customModels && req.body) {
  83 + try {
  84 + const clonedBody = await req.text();
  85 + fetchOptions.body = clonedBody;
  86 +
  87 + const jsonBody = JSON.parse(clonedBody) as { model?: string };
  88 +
  89 + // not undefined and is false
  90 + if (
  91 + isModelNotavailableInServer(
  92 + serverConfig.customModels,
  93 + jsonBody?.model as string,
  94 + ServiceProvider.DeepSeek as string,
  95 + )
  96 + ) {
  97 + return NextResponse.json(
  98 + {
  99 + error: true,
  100 + message: `you are not allowed to use ${jsonBody?.model} model`,
  101 + },
  102 + {
  103 + status: 403,
  104 + },
  105 + );
  106 + }
  107 + } catch (e) {
  108 + console.error(`[DeepSeek] filter`, e);
  109 + }
  110 + }
  111 + try {
  112 + const res = await fetch(fetchUrl, fetchOptions);
  113 +
  114 + // to prevent browser prompt for credentials
  115 + const newHeaders = new Headers(res.headers);
  116 + newHeaders.delete("www-authenticate");
  117 + // to disable nginx buffering
  118 + newHeaders.set("X-Accel-Buffering", "no");
  119 +
  120 + return new Response(res.body, {
  121 + status: res.status,
  122 + statusText: res.statusText,
  123 + headers: newHeaders,
  124 + });
  125 + } finally {
  126 + clearTimeout(timeoutId);
  127 + }
  128 +}
  1 +import { getServerSideConfig } from "@/app/config/server";
  2 +import {
  3 + CHATGLM_BASE_URL,
  4 + ApiPath,
  5 + ModelProvider,
  6 + ServiceProvider,
  7 +} from "@/app/constant";
  8 +import { prettyObject } from "@/app/utils/format";
  9 +import { NextRequest, NextResponse } from "next/server";
  10 +import { auth } from "@/app/api/auth";
  11 +import { isModelNotavailableInServer } from "@/app/utils/model";
  12 +
  13 +const serverConfig = getServerSideConfig();
  14 +
  15 +export async function handle(
  16 + req: NextRequest,
  17 + { params }: { params: { path: string[] } },
  18 +) {
  19 + console.log("[GLM Route] params ", params);
  20 +
  21 + if (req.method === "OPTIONS") {
  22 + return NextResponse.json({ body: "OK" }, { status: 200 });
  23 + }
  24 +
  25 + const authResult = auth(req, ModelProvider.ChatGLM);
  26 + if (authResult.error) {
  27 + return NextResponse.json(authResult, {
  28 + status: 401,
  29 + });
  30 + }
  31 +
  32 + try {
  33 + const response = await request(req);
  34 + return response;
  35 + } catch (e) {
  36 + console.error("[GLM] ", e);
  37 + return NextResponse.json(prettyObject(e));
  38 + }
  39 +}
  40 +
  41 +async function request(req: NextRequest) {
  42 + const controller = new AbortController();
  43 +
  44 + // alibaba use base url or just remove the path
  45 + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.ChatGLM, "");
  46 +
  47 + let baseUrl = serverConfig.chatglmUrl || CHATGLM_BASE_URL;
  48 +
  49 + if (!baseUrl.startsWith("http")) {
  50 + baseUrl = `https://${baseUrl}`;
  51 + }
  52 +
  53 + if (baseUrl.endsWith("/")) {
  54 + baseUrl = baseUrl.slice(0, -1);
  55 + }
  56 +
  57 + console.log("[Proxy] ", path);
  58 + console.log("[Base Url]", baseUrl);
  59 +
  60 + const timeoutId = setTimeout(
  61 + () => {
  62 + controller.abort();
  63 + },
  64 + 10 * 60 * 1000,
  65 + );
  66 +
  67 + const fetchUrl = `${baseUrl}${path}`;
  68 + console.log("[Fetch Url] ", fetchUrl);
  69 + const fetchOptions: RequestInit = {
  70 + headers: {
  71 + "Content-Type": "application/json",
  72 + Authorization: req.headers.get("Authorization") ?? "",
  73 + },
  74 + method: req.method,
  75 + body: req.body,
  76 + redirect: "manual",
  77 + // @ts-ignore
  78 + duplex: "half",
  79 + signal: controller.signal,
  80 + };
  81 +
  82 + // #1815 try to refuse some request to some models
  83 + if (serverConfig.customModels && req.body) {
  84 + try {
  85 + const clonedBody = await req.text();
  86 + fetchOptions.body = clonedBody;
  87 +
  88 + const jsonBody = JSON.parse(clonedBody) as { model?: string };
  89 +
  90 + // not undefined and is false
  91 + if (
  92 + isModelNotavailableInServer(
  93 + serverConfig.customModels,
  94 + jsonBody?.model as string,
  95 + ServiceProvider.ChatGLM as string,
  96 + )
  97 + ) {
  98 + return NextResponse.json(
  99 + {
  100 + error: true,
  101 + message: `you are not allowed to use ${jsonBody?.model} model`,
  102 + },
  103 + {
  104 + status: 403,
  105 + },
  106 + );
  107 + }
  108 + } catch (e) {
  109 + console.error(`[GLM] filter`, e);
  110 + }
  111 + }
  112 + try {
  113 + const res = await fetch(fetchUrl, fetchOptions);
  114 +
  115 + // to prevent browser prompt for credentials
  116 + const newHeaders = new Headers(res.headers);
  117 + newHeaders.delete("www-authenticate");
  118 + // to disable nginx buffering
  119 + newHeaders.set("X-Accel-Buffering", "no");
  120 +
  121 + return new Response(res.body, {
  122 + status: res.status,
  123 + statusText: res.statusText,
  124 + headers: newHeaders,
  125 + });
  126 + } finally {
  127 + clearTimeout(timeoutId);
  128 + }
  129 +}
  1 +import { NextRequest, NextResponse } from "next/server";
  2 +import { auth } from "./auth";
  3 +import { getServerSideConfig } from "@/app/config/server";
  4 +import { ApiPath, GEMINI_BASE_URL, ModelProvider } from "@/app/constant";
  5 +import { prettyObject } from "@/app/utils/format";
  6 +
  7 +const serverConfig = getServerSideConfig();
  8 +
  9 +export async function handle(
  10 + req: NextRequest,
  11 + { params }: { params: { provider: string; path: string[] } },
  12 +) {
  13 + console.log("[Google Route] params ", params);
  14 +
  15 + if (req.method === "OPTIONS") {
  16 + return NextResponse.json({ body: "OK" }, { status: 200 });
  17 + }
  18 +
  19 + const authResult = auth(req, ModelProvider.GeminiPro);
  20 + if (authResult.error) {
  21 + return NextResponse.json(authResult, {
  22 + status: 401,
  23 + });
  24 + }
  25 +
  26 + const bearToken =
  27 + req.headers.get("x-goog-api-key") || req.headers.get("Authorization") || "";
  28 + const token = bearToken.trim().replaceAll("Bearer ", "").trim();
  29 +
  30 + const apiKey = token ? token : serverConfig.googleApiKey;
  31 +
  32 + if (!apiKey) {
  33 + return NextResponse.json(
  34 + {
  35 + error: true,
  36 + message: `missing GOOGLE_API_KEY in server env vars`,
  37 + },
  38 + {
  39 + status: 401,
  40 + },
  41 + );
  42 + }
  43 + try {
  44 + const response = await request(req, apiKey);
  45 + return response;
  46 + } catch (e) {
  47 + console.error("[Google] ", e);
  48 + return NextResponse.json(prettyObject(e));
  49 + }
  50 +}
  51 +
  52 +export const GET = handle;
  53 +export const POST = handle;
  54 +
  55 +export const runtime = "edge";
  56 +export const preferredRegion = [
  57 + "bom1",
  58 + "cle1",
  59 + "cpt1",
  60 + "gru1",
  61 + "hnd1",
  62 + "iad1",
  63 + "icn1",
  64 + "kix1",
  65 + "pdx1",
  66 + "sfo1",
  67 + "sin1",
  68 + "syd1",
  69 +];
  70 +
  71 +async function request(req: NextRequest, apiKey: string) {
  72 + const controller = new AbortController();
  73 +
  74 + let baseUrl = serverConfig.googleUrl || GEMINI_BASE_URL;
  75 +
  76 + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Google, "");
  77 +
  78 + if (!baseUrl.startsWith("http")) {
  79 + baseUrl = `https://${baseUrl}`;
  80 + }
  81 +
  82 + if (baseUrl.endsWith("/")) {
  83 + baseUrl = baseUrl.slice(0, -1);
  84 + }
  85 +
  86 + console.log("[Proxy] ", path);
  87 + console.log("[Base Url]", baseUrl);
  88 +
  89 + const timeoutId = setTimeout(
  90 + () => {
  91 + controller.abort();
  92 + },
  93 + 10 * 60 * 1000,
  94 + );
  95 + const fetchUrl = `${baseUrl}${path}${
  96 + req?.nextUrl?.searchParams?.get("alt") === "sse" ? "?alt=sse" : ""
  97 + }`;
  98 +
  99 + console.log("[Fetch Url] ", fetchUrl);
  100 + const fetchOptions: RequestInit = {
  101 + headers: {
  102 + "Content-Type": "application/json",
  103 + "Cache-Control": "no-store",
  104 + "x-goog-api-key":
  105 + req.headers.get("x-goog-api-key") ||
  106 + (req.headers.get("Authorization") ?? "").replace("Bearer ", ""),
  107 + },
  108 + method: req.method,
  109 + body: req.body,
  110 + // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  111 + redirect: "manual",
  112 + // @ts-ignore
  113 + duplex: "half",
  114 + signal: controller.signal,
  115 + };
  116 +
  117 + try {
  118 + const res = await fetch(fetchUrl, fetchOptions);
  119 + // to prevent browser prompt for credentials
  120 + const newHeaders = new Headers(res.headers);
  121 + newHeaders.delete("www-authenticate");
  122 + // to disable nginx buffering
  123 + newHeaders.set("X-Accel-Buffering", "no");
  124 +
  125 + return new Response(res.body, {
  126 + status: res.status,
  127 + statusText: res.statusText,
  128 + headers: newHeaders,
  129 + });
  130 + } finally {
  131 + clearTimeout(timeoutId);
  132 + }
  133 +}
  1 +import { getServerSideConfig } from "@/app/config/server";
  2 +import {
  3 + IFLYTEK_BASE_URL,
  4 + ApiPath,
  5 + ModelProvider,
  6 + ServiceProvider,
  7 +} from "@/app/constant";
  8 +import { prettyObject } from "@/app/utils/format";
  9 +import { NextRequest, NextResponse } from "next/server";
  10 +import { auth } from "@/app/api/auth";
  11 +import { isModelNotavailableInServer } from "@/app/utils/model";
  12 +// iflytek
  13 +
  14 +const serverConfig = getServerSideConfig();
  15 +
  16 +export async function handle(
  17 + req: NextRequest,
  18 + { params }: { params: { path: string[] } },
  19 +) {
  20 + console.log("[Iflytek Route] params ", params);
  21 +
  22 + if (req.method === "OPTIONS") {
  23 + return NextResponse.json({ body: "OK" }, { status: 200 });
  24 + }
  25 +
  26 + const authResult = auth(req, ModelProvider.Iflytek);
  27 + if (authResult.error) {
  28 + return NextResponse.json(authResult, {
  29 + status: 401,
  30 + });
  31 + }
  32 +
  33 + try {
  34 + const response = await request(req);
  35 + return response;
  36 + } catch (e) {
  37 + console.error("[Iflytek] ", e);
  38 + return NextResponse.json(prettyObject(e));
  39 + }
  40 +}
  41 +
  42 +async function request(req: NextRequest) {
  43 + const controller = new AbortController();
  44 +
  45 + // iflytek use base url or just remove the path
  46 + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Iflytek, "");
  47 +
  48 + let baseUrl = serverConfig.iflytekUrl || IFLYTEK_BASE_URL;
  49 +
  50 + if (!baseUrl.startsWith("http")) {
  51 + baseUrl = `https://${baseUrl}`;
  52 + }
  53 +
  54 + if (baseUrl.endsWith("/")) {
  55 + baseUrl = baseUrl.slice(0, -1);
  56 + }
  57 +
  58 + console.log("[Proxy] ", path);
  59 + console.log("[Base Url]", baseUrl);
  60 +
  61 + const timeoutId = setTimeout(
  62 + () => {
  63 + controller.abort();
  64 + },
  65 + 10 * 60 * 1000,
  66 + );
  67 +
  68 + const fetchUrl = `${baseUrl}${path}`;
  69 + const fetchOptions: RequestInit = {
  70 + headers: {
  71 + "Content-Type": "application/json",
  72 + Authorization: req.headers.get("Authorization") ?? "",
  73 + },
  74 + method: req.method,
  75 + body: req.body,
  76 + redirect: "manual",
  77 + // @ts-ignore
  78 + duplex: "half",
  79 + signal: controller.signal,
  80 + };
  81 +
  82 + // try to refuse some request to some models
  83 + if (serverConfig.customModels && req.body) {
  84 + try {
  85 + const clonedBody = await req.text();
  86 + fetchOptions.body = clonedBody;
  87 +
  88 + const jsonBody = JSON.parse(clonedBody) as { model?: string };
  89 +
  90 + // not undefined and is false
  91 + if (
  92 + isModelNotavailableInServer(
  93 + serverConfig.customModels,
  94 + jsonBody?.model as string,
  95 + ServiceProvider.Iflytek as string,
  96 + )
  97 + ) {
  98 + return NextResponse.json(
  99 + {
  100 + error: true,
  101 + message: `you are not allowed to use ${jsonBody?.model} model`,
  102 + },
  103 + {
  104 + status: 403,
  105 + },
  106 + );
  107 + }
  108 + } catch (e) {
  109 + console.error(`[Iflytek] filter`, e);
  110 + }
  111 + }
  112 + try {
  113 + const res = await fetch(fetchUrl, fetchOptions);
  114 +
  115 + // to prevent browser prompt for credentials
  116 + const newHeaders = new Headers(res.headers);
  117 + newHeaders.delete("www-authenticate");
  118 + // to disable nginx buffering
  119 + newHeaders.set("X-Accel-Buffering", "no");
  120 +
  121 + return new Response(res.body, {
  122 + status: res.status,
  123 + statusText: res.statusText,
  124 + headers: newHeaders,
  125 + });
  126 + } finally {
  127 + clearTimeout(timeoutId);
  128 + }
  129 +}
  1 +import { getServerSideConfig } from "@/app/config/server";
  2 +import {
  3 + MOONSHOT_BASE_URL,
  4 + ApiPath,
  5 + ModelProvider,
  6 + ServiceProvider,
  7 +} from "@/app/constant";
  8 +import { prettyObject } from "@/app/utils/format";
  9 +import { NextRequest, NextResponse } from "next/server";
  10 +import { auth } from "@/app/api/auth";
  11 +import { isModelNotavailableInServer } from "@/app/utils/model";
  12 +
  13 +const serverConfig = getServerSideConfig();
  14 +
  15 +export async function handle(
  16 + req: NextRequest,
  17 + { params }: { params: { path: string[] } },
  18 +) {
  19 + console.log("[Moonshot Route] params ", params);
  20 +
  21 + if (req.method === "OPTIONS") {
  22 + return NextResponse.json({ body: "OK" }, { status: 200 });
  23 + }
  24 +
  25 + const authResult = auth(req, ModelProvider.Moonshot);
  26 + if (authResult.error) {
  27 + return NextResponse.json(authResult, {
  28 + status: 401,
  29 + });
  30 + }
  31 +
  32 + try {
  33 + const response = await request(req);
  34 + return response;
  35 + } catch (e) {
  36 + console.error("[Moonshot] ", e);
  37 + return NextResponse.json(prettyObject(e));
  38 + }
  39 +}
  40 +
  41 +async function request(req: NextRequest) {
  42 + const controller = new AbortController();
  43 +
  44 + // alibaba use base url or just remove the path
  45 + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Moonshot, "");
  46 +
  47 + let baseUrl = serverConfig.moonshotUrl || MOONSHOT_BASE_URL;
  48 +
  49 + if (!baseUrl.startsWith("http")) {
  50 + baseUrl = `https://${baseUrl}`;
  51 + }
  52 +
  53 + if (baseUrl.endsWith("/")) {
  54 + baseUrl = baseUrl.slice(0, -1);
  55 + }
  56 +
  57 + console.log("[Proxy] ", path);
  58 + console.log("[Base Url]", baseUrl);
  59 +
  60 + const timeoutId = setTimeout(
  61 + () => {
  62 + controller.abort();
  63 + },
  64 + 10 * 60 * 1000,
  65 + );
  66 +
  67 + const fetchUrl = `${baseUrl}${path}`;
  68 + const fetchOptions: RequestInit = {
  69 + headers: {
  70 + "Content-Type": "application/json",
  71 + Authorization: req.headers.get("Authorization") ?? "",
  72 + },
  73 + method: req.method,
  74 + body: req.body,
  75 + redirect: "manual",
  76 + // @ts-ignore
  77 + duplex: "half",
  78 + signal: controller.signal,
  79 + };
  80 +
  81 + // #1815 try to refuse some request to some models
  82 + if (serverConfig.customModels && req.body) {
  83 + try {
  84 + const clonedBody = await req.text();
  85 + fetchOptions.body = clonedBody;
  86 +
  87 + const jsonBody = JSON.parse(clonedBody) as { model?: string };
  88 +
  89 + // not undefined and is false
  90 + if (
  91 + isModelNotavailableInServer(
  92 + serverConfig.customModels,
  93 + jsonBody?.model as string,
  94 + ServiceProvider.Moonshot as string,
  95 + )
  96 + ) {
  97 + return NextResponse.json(
  98 + {
  99 + error: true,
  100 + message: `you are not allowed to use ${jsonBody?.model} model`,
  101 + },
  102 + {
  103 + status: 403,
  104 + },
  105 + );
  106 + }
  107 + } catch (e) {
  108 + console.error(`[Moonshot] filter`, e);
  109 + }
  110 + }
  111 + try {
  112 + const res = await fetch(fetchUrl, fetchOptions);
  113 +
  114 + // to prevent browser prompt for credentials
  115 + const newHeaders = new Headers(res.headers);
  116 + newHeaders.delete("www-authenticate");
  117 + // to disable nginx buffering
  118 + newHeaders.set("X-Accel-Buffering", "no");
  119 +
  120 + return new Response(res.body, {
  121 + status: res.status,
  122 + statusText: res.statusText,
  123 + headers: newHeaders,
  124 + });
  125 + } finally {
  126 + clearTimeout(timeoutId);
  127 + }
  128 +}
  1 +import { type OpenAIListModelResponse } from "@/app/client/platforms/openai";
  2 +import { getServerSideConfig } from "@/app/config/server";
  3 +import { ModelProvider, OpenaiPath } from "@/app/constant";
  4 +import { prettyObject } from "@/app/utils/format";
  5 +import { NextRequest, NextResponse } from "next/server";
  6 +import { auth } from "./auth";
  7 +import { requestOpenai } from "./common";
  8 +
  9 +const ALLOWED_PATH = new Set(Object.values(OpenaiPath));
  10 +
  11 +function getModels(remoteModelRes: OpenAIListModelResponse) {
  12 + const config = getServerSideConfig();
  13 +
  14 + if (config.disableGPT4) {
  15 + remoteModelRes.data = remoteModelRes.data.filter(
  16 + (m) =>
  17 + !(
  18 + m.id.startsWith("gpt-4") ||
  19 + m.id.startsWith("chatgpt-4o") ||
  20 + m.id.startsWith("o1") ||
  21 + m.id.startsWith("o3")
  22 + ) || m.id.startsWith("gpt-4o-mini"),
  23 + );
  24 + }
  25 +
  26 + return remoteModelRes;
  27 +}
  28 +
  29 +export async function handle(
  30 + req: NextRequest,
  31 + { params }: { params: { path: string[] } },
  32 +) {
  33 + console.log("------------------------------------进入opanai handle")
  34 + console.log("[OpenAI Route] params ", params);
  35 +
  36 + if (req.method === "OPTIONS") {
  37 + return NextResponse.json({ body: "OK" }, { status: 200 });
  38 + }
  39 +
  40 + const subpath = params.path.join("/");
  41 +
  42 + if (!ALLOWED_PATH.has(subpath)) {
  43 + console.log("[OpenAI Route] forbidden path ", subpath);
  44 + return NextResponse.json(
  45 + {
  46 + error: true,
  47 + msg: "you are not allowed to request " + subpath,
  48 + },
  49 + {
  50 + status: 403,
  51 + },
  52 + );
  53 + }
  54 +
  55 + const authResult = auth(req, ModelProvider.GPT);
  56 + if (authResult.error) {
  57 + return NextResponse.json(authResult, {
  58 + status: 401,
  59 + });
  60 + }
  61 +
  62 + try {
  63 + const response = await requestOpenai(req);
  64 +
  65 + // list models
  66 + if (subpath === OpenaiPath.ListModelPath && response.status === 200) {
  67 + const resJson = (await response.json()) as OpenAIListModelResponse;
  68 + const availableModels = getModels(resJson);
  69 + return NextResponse.json(availableModels, {
  70 + status: response.status,
  71 + });
  72 + }
  73 + return response;
  74 + } catch (e) {
  75 + console.error("[OpenAI] ", e);
  76 + return NextResponse.json(prettyObject(e));
  77 + }
  78 +}
  1 +import { NextRequest, NextResponse } from "next/server";
  2 +import { getServerSideConfig } from "@/app/config/server";
  3 +
  4 +export async function handle(
  5 + req: NextRequest,
  6 + { params }: { params: { path: string[] } },
  7 +) {
  8 + console.log("[Proxy Route] params ", params);
  9 +
  10 + if (req.method === "OPTIONS") {
  11 + return NextResponse.json({ body: "OK" }, { status: 200 });
  12 + }
  13 + const serverConfig = getServerSideConfig();
  14 +
  15 + // remove path params from searchParams
  16 + req.nextUrl.searchParams.delete("path");
  17 + req.nextUrl.searchParams.delete("provider");
  18 +
  19 + const subpath = params.path.join("/");
  20 + const fetchUrl = `${req.headers.get(
  21 + "x-base-url",
  22 + )}/${subpath}?${req.nextUrl.searchParams.toString()}`;
  23 + const skipHeaders = ["connection", "host", "origin", "referer", "cookie"];
  24 + const headers = new Headers(
  25 + Array.from(req.headers.entries()).filter((item) => {
  26 + if (
  27 + item[0].indexOf("x-") > -1 ||
  28 + item[0].indexOf("sec-") > -1 ||
  29 + skipHeaders.includes(item[0])
  30 + ) {
  31 + return false;
  32 + }
  33 + return true;
  34 + }),
  35 + );
  36 + // if dalle3 use openai api key
  37 + const baseUrl = req.headers.get("x-base-url");
  38 + if (baseUrl?.includes("api.openai.com")) {
  39 + if (!serverConfig.apiKey) {
  40 + return NextResponse.json(
  41 + { error: "OpenAI API key not configured" },
  42 + { status: 500 },
  43 + );
  44 + }
  45 + headers.set("Authorization", `Bearer ${serverConfig.apiKey}`);
  46 + }
  47 +
  48 + const controller = new AbortController();
  49 + const fetchOptions: RequestInit = {
  50 + headers,
  51 + method: req.method,
  52 + body: req.body,
  53 + // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  54 + redirect: "manual",
  55 + // @ts-ignore
  56 + duplex: "half",
  57 + signal: controller.signal,
  58 + };
  59 +
  60 + const timeoutId = setTimeout(
  61 + () => {
  62 + controller.abort();
  63 + },
  64 + 10 * 60 * 1000,
  65 + );
  66 +
  67 + try {
  68 + const res = await fetch(fetchUrl, fetchOptions);
  69 + // to prevent browser prompt for credentials
  70 + const newHeaders = new Headers(res.headers);
  71 + newHeaders.delete("www-authenticate");
  72 + // to disable nginx buffering
  73 + newHeaders.set("X-Accel-Buffering", "no");
  74 +
  75 + // The latest version of the OpenAI API forced the content-encoding to be "br" in json response
  76 + // So if the streaming is disabled, we need to remove the content-encoding header
  77 + // Because Vercel uses gzip to compress the response, if we don't remove the content-encoding header
  78 + // The browser will try to decode the response with brotli and fail
  79 + newHeaders.delete("content-encoding");
  80 +
  81 + return new Response(res.body, {
  82 + status: res.status,
  83 + statusText: res.statusText,
  84 + headers: newHeaders,
  85 + });
  86 + } finally {
  87 + clearTimeout(timeoutId);
  88 + }
  89 +}
  1 +import { getServerSideConfig } from "@/app/config/server";
  2 +import {
  3 + SILICONFLOW_BASE_URL,
  4 + ApiPath,
  5 + ModelProvider,
  6 + ServiceProvider,
  7 +} from "@/app/constant";
  8 +import { prettyObject } from "@/app/utils/format";
  9 +import { NextRequest, NextResponse } from "next/server";
  10 +import { auth } from "@/app/api/auth";
  11 +import { isModelNotavailableInServer } from "@/app/utils/model";
  12 +
  13 +const serverConfig = getServerSideConfig();
  14 +
  15 +export async function handle(
  16 + req: NextRequest,
  17 + { params }: { params: { path: string[] } },
  18 +) {
  19 + console.log("[SiliconFlow Route] params ", params);
  20 +
  21 + if (req.method === "OPTIONS") {
  22 + return NextResponse.json({ body: "OK" }, { status: 200 });
  23 + }
  24 +
  25 + const authResult = auth(req, ModelProvider.SiliconFlow);
  26 + if (authResult.error) {
  27 + return NextResponse.json(authResult, {
  28 + status: 401,
  29 + });
  30 + }
  31 +
  32 + try {
  33 + const response = await request(req);
  34 + return response;
  35 + } catch (e) {
  36 + console.error("[SiliconFlow] ", e);
  37 + return NextResponse.json(prettyObject(e));
  38 + }
  39 +}
  40 +
  41 +async function request(req: NextRequest) {
  42 + const controller = new AbortController();
  43 +
  44 + // alibaba use base url or just remove the path
  45 + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.SiliconFlow, "");
  46 +
  47 + let baseUrl = serverConfig.siliconFlowUrl || SILICONFLOW_BASE_URL;
  48 +
  49 + if (!baseUrl.startsWith("http")) {
  50 + baseUrl = `https://${baseUrl}`;
  51 + }
  52 +
  53 + if (baseUrl.endsWith("/")) {
  54 + baseUrl = baseUrl.slice(0, -1);
  55 + }
  56 +
  57 + console.log("[Proxy] ", path);
  58 + console.log("[Base Url]", baseUrl);
  59 +
  60 + const timeoutId = setTimeout(
  61 + () => {
  62 + controller.abort();
  63 + },
  64 + 10 * 60 * 1000,
  65 + );
  66 +
  67 + const fetchUrl = `${baseUrl}${path}`;
  68 + const fetchOptions: RequestInit = {
  69 + headers: {
  70 + "Content-Type": "application/json",
  71 + Authorization: req.headers.get("Authorization") ?? "",
  72 + },
  73 + method: req.method,
  74 + body: req.body,
  75 + redirect: "manual",
  76 + // @ts-ignore
  77 + duplex: "half",
  78 + signal: controller.signal,
  79 + };
  80 +
  81 + // #1815 try to refuse some request to some models
  82 + if (serverConfig.customModels && req.body) {
  83 + try {
  84 + const clonedBody = await req.text();
  85 + fetchOptions.body = clonedBody;
  86 +
  87 + const jsonBody = JSON.parse(clonedBody) as { model?: string };
  88 +
  89 + // not undefined and is false
  90 + if (
  91 + isModelNotavailableInServer(
  92 + serverConfig.customModels,
  93 + jsonBody?.model as string,
  94 + ServiceProvider.SiliconFlow as string,
  95 + )
  96 + ) {
  97 + return NextResponse.json(
  98 + {
  99 + error: true,
  100 + message: `you are not allowed to use ${jsonBody?.model} model`,
  101 + },
  102 + {
  103 + status: 403,
  104 + },
  105 + );
  106 + }
  107 + } catch (e) {
  108 + console.error(`[SiliconFlow] filter`, e);
  109 + }
  110 + }
  111 + try {
  112 + const res = await fetch(fetchUrl, fetchOptions);
  113 +
  114 + // to prevent browser prompt for credentials
  115 + const newHeaders = new Headers(res.headers);
  116 + newHeaders.delete("www-authenticate");
  117 + // to disable nginx buffering
  118 + newHeaders.set("X-Accel-Buffering", "no");
  119 +
  120 + return new Response(res.body, {
  121 + status: res.status,
  122 + statusText: res.statusText,
  123 + headers: newHeaders,
  124 + });
  125 + } finally {
  126 + clearTimeout(timeoutId);
  127 + }
  128 +}
  1 +import { NextRequest, NextResponse } from "next/server";
  2 +import { getServerSideConfig } from "@/app/config/server";
  3 +import { ModelProvider, STABILITY_BASE_URL } from "@/app/constant";
  4 +import { auth } from "@/app/api/auth";
  5 +
  6 +export async function handle(
  7 + req: NextRequest,
  8 + { params }: { params: { path: string[] } },
  9 +) {
  10 + console.log("[Stability] params ", params);
  11 +
  12 + if (req.method === "OPTIONS") {
  13 + return NextResponse.json({ body: "OK" }, { status: 200 });
  14 + }
  15 +
  16 + const controller = new AbortController();
  17 +
  18 + const serverConfig = getServerSideConfig();
  19 +
  20 + let baseUrl = serverConfig.stabilityUrl || STABILITY_BASE_URL;
  21 +
  22 + if (!baseUrl.startsWith("http")) {
  23 + baseUrl = `https://${baseUrl}`;
  24 + }
  25 +
  26 + if (baseUrl.endsWith("/")) {
  27 + baseUrl = baseUrl.slice(0, -1);
  28 + }
  29 +
  30 + let path = `${req.nextUrl.pathname}`.replaceAll("/api/stability/", "");
  31 +
  32 + console.log("[Stability Proxy] ", path);
  33 + console.log("[Stability Base Url]", baseUrl);
  34 +
  35 + const timeoutId = setTimeout(
  36 + () => {
  37 + controller.abort();
  38 + },
  39 + 10 * 60 * 1000,
  40 + );
  41 +
  42 + const authResult = auth(req, ModelProvider.Stability);
  43 +
  44 + if (authResult.error) {
  45 + return NextResponse.json(authResult, {
  46 + status: 401,
  47 + });
  48 + }
  49 +
  50 + const bearToken = req.headers.get("Authorization") ?? "";
  51 + const token = bearToken.trim().replaceAll("Bearer ", "").trim();
  52 +
  53 + const key = token ? token : serverConfig.stabilityApiKey;
  54 +
  55 + if (!key) {
  56 + return NextResponse.json(
  57 + {
  58 + error: true,
  59 + message: `missing STABILITY_API_KEY in server env vars`,
  60 + },
  61 + {
  62 + status: 401,
  63 + },
  64 + );
  65 + }
  66 +
  67 + const fetchUrl = `${baseUrl}/${path}`;
  68 + console.log("[Stability Url] ", fetchUrl);
  69 + const fetchOptions: RequestInit = {
  70 + headers: {
  71 + "Content-Type": req.headers.get("Content-Type") || "multipart/form-data",
  72 + Accept: req.headers.get("Accept") || "application/json",
  73 + Authorization: `Bearer ${key}`,
  74 + },
  75 + method: req.method,
  76 + body: req.body,
  77 + // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  78 + redirect: "manual",
  79 + // @ts-ignore
  80 + duplex: "half",
  81 + signal: controller.signal,
  82 + };
  83 +
  84 + try {
  85 + const res = await fetch(fetchUrl, fetchOptions);
  86 + // to prevent browser prompt for credentials
  87 + const newHeaders = new Headers(res.headers);
  88 + newHeaders.delete("www-authenticate");
  89 + // to disable nginx buffering
  90 + newHeaders.set("X-Accel-Buffering", "no");
  91 + return new Response(res.body, {
  92 + status: res.status,
  93 + statusText: res.statusText,
  94 + headers: newHeaders,
  95 + });
  96 + } finally {
  97 + clearTimeout(timeoutId);
  98 + }
  99 +}
  1 +import { getServerSideConfig } from "@/app/config/server";
  2 +import { TENCENT_BASE_URL, ModelProvider } from "@/app/constant";
  3 +import { prettyObject } from "@/app/utils/format";
  4 +import { NextRequest, NextResponse } from "next/server";
  5 +import { auth } from "@/app/api/auth";
  6 +import { getHeader } from "@/app/utils/tencent";
  7 +
  8 +const serverConfig = getServerSideConfig();
  9 +
  10 +async function handle(
  11 + req: NextRequest,
  12 + { params }: { params: { path: string[] } },
  13 +) {
  14 + console.log("[Tencent Route] params ", params);
  15 +
  16 + if (req.method === "OPTIONS") {
  17 + return NextResponse.json({ body: "OK" }, { status: 200 });
  18 + }
  19 +
  20 + const authResult = auth(req, ModelProvider.Hunyuan);
  21 + if (authResult.error) {
  22 + return NextResponse.json(authResult, {
  23 + status: 401,
  24 + });
  25 + }
  26 +
  27 + try {
  28 + const response = await request(req);
  29 + return response;
  30 + } catch (e) {
  31 + console.error("[Tencent] ", e);
  32 + return NextResponse.json(prettyObject(e));
  33 + }
  34 +}
  35 +
  36 +export const GET = handle;
  37 +export const POST = handle;
  38 +
  39 +export const runtime = "edge";
  40 +export const preferredRegion = [
  41 + "arn1",
  42 + "bom1",
  43 + "cdg1",
  44 + "cle1",
  45 + "cpt1",
  46 + "dub1",
  47 + "fra1",
  48 + "gru1",
  49 + "hnd1",
  50 + "iad1",
  51 + "icn1",
  52 + "kix1",
  53 + "lhr1",
  54 + "pdx1",
  55 + "sfo1",
  56 + "sin1",
  57 + "syd1",
  58 +];
  59 +
  60 +async function request(req: NextRequest) {
  61 + const controller = new AbortController();
  62 +
  63 + let baseUrl = serverConfig.tencentUrl || TENCENT_BASE_URL;
  64 +
  65 + if (!baseUrl.startsWith("http")) {
  66 + baseUrl = `https://${baseUrl}`;
  67 + }
  68 +
  69 + if (baseUrl.endsWith("/")) {
  70 + baseUrl = baseUrl.slice(0, -1);
  71 + }
  72 +
  73 + console.log("[Base Url]", baseUrl);
  74 +
  75 + const timeoutId = setTimeout(
  76 + () => {
  77 + controller.abort();
  78 + },
  79 + 10 * 60 * 1000,
  80 + );
  81 +
  82 + const fetchUrl = baseUrl;
  83 +
  84 + const body = await req.text();
  85 + const headers = await getHeader(
  86 + body,
  87 + serverConfig.tencentSecretId as string,
  88 + serverConfig.tencentSecretKey as string,
  89 + );
  90 + const fetchOptions: RequestInit = {
  91 + headers,
  92 + method: req.method,
  93 + body,
  94 + redirect: "manual",
  95 + // @ts-ignore
  96 + duplex: "half",
  97 + signal: controller.signal,
  98 + };
  99 +
  100 + try {
  101 + const res = await fetch(fetchUrl, fetchOptions);
  102 +
  103 + // to prevent browser prompt for credentials
  104 + const newHeaders = new Headers(res.headers);
  105 + newHeaders.delete("www-authenticate");
  106 + // to disable nginx buffering
  107 + newHeaders.set("X-Accel-Buffering", "no");
  108 +
  109 + return new Response(res.body, {
  110 + status: res.status,
  111 + statusText: res.statusText,
  112 + headers: newHeaders,
  113 + });
  114 + } finally {
  115 + clearTimeout(timeoutId);
  116 + }
  117 +}
  1 +import { NextRequest, NextResponse } from "next/server";
  2 +
  3 +async function handle(
  4 + req: NextRequest,
  5 + { params }: { params: { action: string; key: string[] } },
  6 +) {
  7 + const requestUrl = new URL(req.url);
  8 + const endpoint = requestUrl.searchParams.get("endpoint");
  9 +
  10 + if (req.method === "OPTIONS") {
  11 + return NextResponse.json({ body: "OK" }, { status: 200 });
  12 + }
  13 + const [...key] = params.key;
  14 + // only allow to request to *.upstash.io
  15 + if (!endpoint || !new URL(endpoint).hostname.endsWith(".upstash.io")) {
  16 + return NextResponse.json(
  17 + {
  18 + error: true,
  19 + msg: "you are not allowed to request " + params.key.join("/"),
  20 + },
  21 + {
  22 + status: 403,
  23 + },
  24 + );
  25 + }
  26 +
  27 + // only allow upstash get and set method
  28 + if (params.action !== "get" && params.action !== "set") {
  29 + console.log("[Upstash Route] forbidden action ", params.action);
  30 + return NextResponse.json(
  31 + {
  32 + error: true,
  33 + msg: "you are not allowed to request " + params.action,
  34 + },
  35 + {
  36 + status: 403,
  37 + },
  38 + );
  39 + }
  40 +
  41 + const targetUrl = `${endpoint}/${params.action}/${params.key.join("/")}`;
  42 +
  43 + const method = req.method;
  44 + const shouldNotHaveBody = ["get", "head"].includes(
  45 + method?.toLowerCase() ?? "",
  46 + );
  47 +
  48 + const fetchOptions: RequestInit = {
  49 + headers: {
  50 + authorization: req.headers.get("authorization") ?? "",
  51 + },
  52 + body: shouldNotHaveBody ? null : req.body,
  53 + method,
  54 + // @ts-ignore
  55 + duplex: "half",
  56 + };
  57 +
  58 + console.log("[Upstash Proxy]", targetUrl, fetchOptions);
  59 + const fetchResult = await fetch(targetUrl, fetchOptions);
  60 +
  61 + console.log("[Any Proxy]", targetUrl, {
  62 + status: fetchResult.status,
  63 + statusText: fetchResult.statusText,
  64 + });
  65 +
  66 + return fetchResult;
  67 +}
  68 +
  69 +export const POST = handle;
  70 +export const GET = handle;
  71 +export const OPTIONS = handle;
  72 +
  73 +export const runtime = "edge";
  1 +import { NextRequest, NextResponse } from "next/server";
  2 +import { STORAGE_KEY, internalAllowedWebDavEndpoints } from "../../../constant";
  3 +import { getServerSideConfig } from "@/app/config/server";
  4 +
  5 +const config = getServerSideConfig();
  6 +
  7 +const mergedAllowedWebDavEndpoints = [
  8 + ...internalAllowedWebDavEndpoints,
  9 + ...config.allowedWebDavEndpoints,
  10 +].filter((domain) => Boolean(domain.trim()));
  11 +
  12 +const normalizeUrl = (url: string) => {
  13 + try {
  14 + return new URL(url);
  15 + } catch (err) {
  16 + return null;
  17 + }
  18 +};
  19 +
  20 +async function handle(
  21 + req: NextRequest,
  22 + { params }: { params: { path: string[] } },
  23 +) {
  24 + if (req.method === "OPTIONS") {
  25 + return NextResponse.json({ body: "OK" }, { status: 200 });
  26 + }
  27 + const folder = STORAGE_KEY;
  28 + const fileName = `${folder}/backup.json`;
  29 +
  30 + const requestUrl = new URL(req.url);
  31 + let endpoint = requestUrl.searchParams.get("endpoint");
  32 + let proxy_method = requestUrl.searchParams.get("proxy_method") || req.method;
  33 +
  34 + // Validate the endpoint to prevent potential SSRF attacks
  35 + if (
  36 + !endpoint ||
  37 + !mergedAllowedWebDavEndpoints.some((allowedEndpoint) => {
  38 + const normalizedAllowedEndpoint = normalizeUrl(allowedEndpoint);
  39 + const normalizedEndpoint = normalizeUrl(endpoint as string);
  40 +
  41 + return (
  42 + normalizedEndpoint &&
  43 + normalizedEndpoint.hostname === normalizedAllowedEndpoint?.hostname &&
  44 + normalizedEndpoint.pathname.startsWith(
  45 + normalizedAllowedEndpoint.pathname,
  46 + )
  47 + );
  48 + })
  49 + ) {
  50 + return NextResponse.json(
  51 + {
  52 + error: true,
  53 + msg: "Invalid endpoint",
  54 + },
  55 + {
  56 + status: 400,
  57 + },
  58 + );
  59 + }
  60 +
  61 + if (!endpoint?.endsWith("/")) {
  62 + endpoint += "/";
  63 + }
  64 +
  65 + const endpointPath = params.path.join("/");
  66 + const targetPath = `${endpoint}${endpointPath}`;
  67 +
  68 + // only allow MKCOL, GET, PUT
  69 + if (
  70 + proxy_method !== "MKCOL" &&
  71 + proxy_method !== "GET" &&
  72 + proxy_method !== "PUT"
  73 + ) {
  74 + return NextResponse.json(
  75 + {
  76 + error: true,
  77 + msg: "you are not allowed to request " + targetPath,
  78 + },
  79 + {
  80 + status: 403,
  81 + },
  82 + );
  83 + }
  84 +
  85 + // for MKCOL request, only allow request ${folder}
  86 + if (proxy_method === "MKCOL" && !targetPath.endsWith(folder)) {
  87 + return NextResponse.json(
  88 + {
  89 + error: true,
  90 + msg: "you are not allowed to request " + targetPath,
  91 + },
  92 + {
  93 + status: 403,
  94 + },
  95 + );
  96 + }
  97 +
  98 + // for GET request, only allow request ending with fileName
  99 + if (proxy_method === "GET" && !targetPath.endsWith(fileName)) {
  100 + return NextResponse.json(
  101 + {
  102 + error: true,
  103 + msg: "you are not allowed to request " + targetPath,
  104 + },
  105 + {
  106 + status: 403,
  107 + },
  108 + );
  109 + }
  110 +
  111 + // for PUT request, only allow request ending with fileName
  112 + if (proxy_method === "PUT" && !targetPath.endsWith(fileName)) {
  113 + return NextResponse.json(
  114 + {
  115 + error: true,
  116 + msg: "you are not allowed to request " + targetPath,
  117 + },
  118 + {
  119 + status: 403,
  120 + },
  121 + );
  122 + }
  123 +
  124 + const targetUrl = targetPath;
  125 +
  126 + const method = proxy_method || req.method;
  127 + const shouldNotHaveBody = ["get", "head"].includes(
  128 + method?.toLowerCase() ?? "",
  129 + );
  130 +
  131 + const fetchOptions: RequestInit = {
  132 + headers: {
  133 + authorization: req.headers.get("authorization") ?? "",
  134 + },
  135 + body: shouldNotHaveBody ? null : req.body,
  136 + redirect: "manual",
  137 + method,
  138 + // @ts-ignore
  139 + duplex: "half",
  140 + };
  141 +
  142 + let fetchResult;
  143 +
  144 + try {
  145 + fetchResult = await fetch(targetUrl, fetchOptions);
  146 + } finally {
  147 + console.log(
  148 + "[Any Proxy]",
  149 + targetUrl,
  150 + {
  151 + method: method,
  152 + },
  153 + {
  154 + status: fetchResult?.status,
  155 + statusText: fetchResult?.statusText,
  156 + },
  157 + );
  158 + }
  159 +
  160 + return fetchResult;
  161 +}
  162 +
  163 +export const PUT = handle;
  164 +export const GET = handle;
  165 +export const OPTIONS = handle;
  166 +
  167 +export const runtime = "edge";