liuzhao521 commited on
Commit ·
4674012
0
Parent(s):
Deploy New API v0.9.25+ (commit b47cf4ef) to HuggingFace Spaces
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreAdded+9
- .env.exampleAdded+76
- .gitattributesAdded+3
- .github/FUNDING.ymlAdded+12
- .github/ISSUE_TEMPLATE/bug_report.mdAdded+26
- .github/ISSUE_TEMPLATE/bug_report_en.mdAdded+26
- .github/ISSUE_TEMPLATE/config.ymlAdded+5
- .github/ISSUE_TEMPLATE/feature_request.mdAdded+21
- .github/ISSUE_TEMPLATE/feature_request_en.mdAdded+22
- .github/PULL_REQUEST_TEMPLATE/pull_request_template.mdAdded+15
- .github/workflows/docker-image-alpha.ymlAdded+151
- .github/workflows/docker-image-arm64.ymlAdded+138
- .github/workflows/electron-build.ymlAdded+141
- .github/workflows/release.ymlAdded+142
- .github/workflows/sync-to-gitee.ymlAdded+91
- .gitignoreAdded+23
- DockerfileAdded+44
- Dockerfile.hfAdded+44
- LICENSEAdded+103
- README.en.mdAdded+447
- README.fr.mdAdded+441
- README.ja.mdAdded+450
- README.mdAdded+459
- VERSIONAdded
- bin/migration_v0.2-v0.3.sqlAdded+6
- bin/migration_v0.3-v0.4.sqlAdded+17
- bin/time_test.shAdded+40
- common/api_type.goAdded+81
- common/audio.goAdded+296
- common/constants.goAdded+204
- common/copy.goAdded+19
- common/crypto.goAdded+32
- common/custom-event.goAdded+87
- common/database.goAdded+15
- common/email-outlook-auth.goAdded+40
- common/email.goAdded+93
- common/embed-file-system.goAdded+43
- common/endpoint_defaults.goAdded+33
- common/endpoint_type.goAdded+43
- common/env.goAdded+38
- common/gin.goAdded+234
- common/go-channel.goAdded+53
- common/gopool.goAdded+25
- common/hash.goAdded+34
- common/init.goAdded+144
- common/ip.goAdded+22
- common/json.goAdded+45
- common/limiter/limiter.goAdded+90
- common/limiter/lua/rate_limit.luaAdded+44
- common/model.goAdded+42
123456789.github.git*.md.vscode.gitignoreMakefiledocs.eslintcache.gocache12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# 端口号# PORT=3000# 前端基础URL# FRONTEND_BASE_URL=https://your-frontend-url.com
# 调试相关配置# 启用pprof# ENABLE_PPROF=true# 启用调试模式# DEBUG=true
# 数据库相关配置# 数据库连接字符串# SQL_DSN=user:password@tcp(127.0.0.1:3306)/dbname?parseTime=true# 日志数据库连接字符串# LOG_SQL_DSN=user:password@tcp(127.0.0.1:3306)/logdb?parseTime=true# SQLite数据库路径# SQLITE_PATH=/path/to/sqlite.db# 数据库最大空闲连接数# SQL_MAX_IDLE_CONNS=100# 数据库最大打开连接数# SQL_MAX_OPEN_CONNS=1000# 数据库连接最大生命周期(秒)# SQL_MAX_LIFETIME=60
# 缓存相关配置# Redis连接字符串# REDIS_CONN_STRING=redis://user:password@localhost:6379/0# 同步频率(单位:秒)# SYNC_FREQUENCY=60# 内存缓存启用# MEMORY_CACHE_ENABLED=true# 渠道更新频率(单位:秒)# CHANNEL_UPDATE_FREQUENCY=30# 批量更新启用# BATCH_UPDATE_ENABLED=true# 批量更新间隔(单位:秒)# BATCH_UPDATE_INTERVAL=5
# 任务和功能配置# 更新任务启用# UPDATE_TASK=true
# 对话超时设置# 所有请求超时时间,单位秒,默认为0,表示不限制# RELAY_TIMEOUT=0# 流模式无响应超时时间,单位秒,如果出现空补全可以尝试改为更大值# STREAMING_TIMEOUT=300
# Gemini 识别图片 最大图片数量# GEMINI_VISION_MAX_IMAGE_NUM=16
# 会话密钥# SESSION_SECRET=random_string
# 其他配置# 生成默认token# GENERATE_DEFAULT_TOKEN=false# Cohere 安全设置# COHERE_SAFETY_SETTING=NONE# 是否统计图片token# GET_MEDIA_TOKEN=true# 是否在非流(stream=false)情况下统计图片token# GET_MEDIA_TOKEN_NOT_STREAM=false# 设置 Dify 渠道是否输出工作流和节点信息到客户端# DIFY_DEBUG=true
# LinuxDo相关配置LINUX_DO_TOKEN_ENDPOINT=https://connect.linux.do/oauth2/tokenLINUX_DO_USER_ENDPOINT=https://connect.linux.do/api/user
# 节点类型# 如果是主节点则为master# NODE_TYPE=master123*.lockb filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.ico filter=lfs diff=lfs merge=lfs -text123456789101112# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]patreon: # Replace with a single Patreon usernameopen_collective: # Replace with a single Open Collective usernameko_fi: # Replace with a single Ko-fi usernametidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babelcommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundryliberapay: # Replace with a single Liberapay usernameissuehunt: # Replace with a single IssueHunt usernameotechie: # Replace with a single Otechie usernamecustom: ['https://afdian.com/a/new-api'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']1234567891011121314151617181920212223242526---name: 报告问题about: 使用简练详细的语言描述你遇到的问题title: ''labels: bugassignees: ''
---
**例行检查**
[//]: # (方框内删除已有的空格,填 x 号)+ [ ] 我已确认目前没有类似 issue+ [ ] 我已确认我已升级到最新版本+ [ ] 我已完整查看过项目 README,尤其是常见问题部分+ [ ] 我理解并愿意跟进此 issue,协助测试和提供反馈 + [ ] 我理解并认可上述内容,并理解项目维护者精力有限,**不遵循规则的 issue 可能会被无视或直接关闭**
**问题描述**
**复现步骤**
**预期结果**
**相关截图**如果没有的话,请删除此节。1234567891011121314151617181920212223242526---name: Bug Reportabout: Describe the issue you encountered with clear and detailed languagetitle: ''labels: bugassignees: ''
---
**Routine Checks**
[//]: # (Remove the space in the box and fill with an x)+ [ ] I have confirmed there are no similar issues currently+ [ ] I have confirmed I have upgraded to the latest version+ [ ] I have thoroughly read the project README, especially the FAQ section+ [ ] I understand and am willing to follow up on this issue, assist with testing and provide feedback + [ ] I understand and acknowledge the above, and understand that project maintainers have limited time and energy, **issues that do not follow the rules may be ignored or closed directly**
**Issue Description**
**Steps to Reproduce**
**Expected Result**
**Related Screenshots**If none, please delete this section.12345blank_issues_enabled: falsecontact_links: - name: 项目群聊 url: https://private-user-images.githubusercontent.com/61247483/283011625-de536a8a-0161-47a7-a0a2-66ef6de81266.jpeg?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTEiLCJleHAiOjE3MDIyMjQzOTAsIm5iZiI6MTcwMjIyNDA5MCwicGF0aCI6Ii82MTI0NzQ4My8yODMwMTE2MjUtZGU1MzZhOGEtMDE2MS00N2E3LWEwYTItNjZlZjZkZTgxMjY2LmpwZWc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBSVdOSllBWDRDU1ZFSDUzQSUyRjIwMjMxMjEwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDIzMTIxMFQxNjAxMzBaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT02MGIxYmM3ZDQyYzBkOTA2ZTYyYmVmMzQ1NjY4NjM1YjY0NTUzNTM5NjE1NDZkYTIzODdhYTk4ZjZjODJmYzY2JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCZhY3Rvcl9pZD0wJmtleV9pZD0wJnJlcG9faWQ9MCJ9.TJ8CTfOSwR0-CHS1KLfomqgL0e4YH1luy8lSLrkv5Zg about: QQ 群:629454374123456789101112131415161718192021---name: 功能请求about: 使用简练详细的语言描述希望加入的新功能title: ''labels: enhancementassignees: ''
---
**例行检查**
[//]: # (方框内删除已有的空格,填 x 号)+ [ ] 我已确认目前没有类似 issue+ [ ] 我已确认我已升级到最新版本+ [ ] 我已完整查看过项目 README,已确定现有版本无法满足需求+ [ ] 我理解并愿意跟进此 issue,协助测试和提供反馈+ [ ] 我理解并认可上述内容,并理解项目维护者精力有限,**不遵循规则的 issue 可能会被无视或直接关闭**
**功能描述**
**应用场景**12345678910111213141516171819202122---name: Feature Requestabout: Describe the new feature you would like to add with clear and detailed languagetitle: ''labels: enhancementassignees: ''
---
**Routine Checks**
[//]: # (Remove the space in the box and fill with an x)+ [ ] I have confirmed there are no similar issues currently+ [ ] I have confirmed I have upgraded to the latest version+ [ ] I have thoroughly read the project README and confirmed the current version cannot meet my needs+ [ ] I understand and am willing to follow up on this issue, assist with testing and provide feedback+ [ ] I understand and acknowledge the above, and understand that project maintainers have limited time and energy, **issues that do not follow the rules may be ignored or closed directly**
**Feature Description**
**Use Case**
123456789101112131415### PR 类型
- [ ] Bug 修复- [ ] 新功能- [ ] 文档更新- [ ] 其他
### PR 是否包含破坏性更新?
- [ ] 是- [ ] 否
### PR 描述
**请在下方详细描述您的 PR,包括目的、实现细节等。**123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151name: Publish Docker image (alpha)
on: push: branches: - alpha workflow_dispatch: inputs: name: description: "reason" required: false
jobs: build_single_arch: name: Build & push (${{ matrix.arch }}) [native] strategy: fail-fast: false matrix: include: - arch: amd64 platform: linux/amd64 runner: ubuntu-latest - arch: arm64 platform: linux/arm64 runner: ubuntu-24.04-arm runs-on: ${{ matrix.runner }} permissions: packages: write contents: read steps: - name: Check out (shallow) uses: actions/checkout@v4 with: fetch-depth: 1
- name: Determine alpha version id: version run: | VERSION="alpha-$(date +'%Y%m%d')-$(git rev-parse --short HEAD)" echo "$VERSION" > VERSION echo "value=$VERSION" >> $GITHUB_OUTPUT echo "VERSION=$VERSION" >> $GITHUB_ENV echo "Publishing version: $VERSION for ${{ matrix.arch }}"
- name: Normalize GHCR repository run: echo "GHCR_REPOSITORY=${GITHUB_REPOSITORY,,}" >> $GITHUB_ENV
- name: Set up Docker Buildx uses: docker/setup-buildx-action@v3
- name: Log in to Docker Hub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Log in to GHCR uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (labels) id: meta uses: docker/metadata-action@v5 with: images: | calciumion/new-api ghcr.io/${{ env.GHCR_REPOSITORY }}
- name: Build & push single-arch (to both registries) uses: docker/build-push-action@v6 with: context: . platforms: ${{ matrix.platform }} push: true tags: | calciumion/new-api:alpha-${{ matrix.arch }} calciumion/new-api:${{ steps.version.outputs.value }}-${{ matrix.arch }} ghcr.io/${{ env.GHCR_REPOSITORY }}:alpha-${{ matrix.arch }} ghcr.io/${{ env.GHCR_REPOSITORY }}:${{ steps.version.outputs.value }}-${{ matrix.arch }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max provenance: false sbom: false
create_manifests: name: Create multi-arch manifests (Docker Hub + GHCR) needs: [build_single_arch] runs-on: ubuntu-latest permissions: packages: write contents: read steps: - name: Check out (shallow) uses: actions/checkout@v4 with: fetch-depth: 1
- name: Normalize GHCR repository run: echo "GHCR_REPOSITORY=${GITHUB_REPOSITORY,,}" >> $GITHUB_ENV
- name: Determine alpha version id: version run: | VERSION="alpha-$(date +'%Y%m%d')-$(git rev-parse --short HEAD)" echo "value=$VERSION" >> $GITHUB_OUTPUT echo "VERSION=$VERSION" >> $GITHUB_ENV
- name: Log in to Docker Hub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Create & push manifest (Docker Hub - alpha) run: | docker buildx imagetools create \ -t calciumion/new-api:alpha \ calciumion/new-api:alpha-amd64 \ calciumion/new-api:alpha-arm64
- name: Create & push manifest (Docker Hub - versioned alpha) run: | docker buildx imagetools create \ -t calciumion/new-api:${VERSION} \ calciumion/new-api:${VERSION}-amd64 \ calciumion/new-api:${VERSION}-arm64
- name: Log in to GHCR uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Create & push manifest (GHCR - alpha) run: | docker buildx imagetools create \ -t ghcr.io/${GHCR_REPOSITORY}:alpha \ ghcr.io/${GHCR_REPOSITORY}:alpha-amd64 \ ghcr.io/${GHCR_REPOSITORY}:alpha-arm64
- name: Create & push manifest (GHCR - versioned alpha) run: | docker buildx imagetools create \ -t ghcr.io/${GHCR_REPOSITORY}:${VERSION} \ ghcr.io/${GHCR_REPOSITORY}:${VERSION}-amd64 \ ghcr.io/${GHCR_REPOSITORY}:${VERSION}-arm64123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138name: Publish Docker image (Multi Registries, native amd64+arm64)
on: push: tags: - '*'
jobs: build_single_arch: name: Build & push (${{ matrix.arch }}) [native] strategy: fail-fast: false matrix: include: - arch: amd64 platform: linux/amd64 runner: ubuntu-latest - arch: arm64 platform: linux/arm64 runner: ubuntu-24.04-arm runs-on: ${{ matrix.runner }}
permissions: packages: write contents: read
steps: - name: Check out (shallow) uses: actions/checkout@v4 with: fetch-depth: 1
- name: Resolve tag & write VERSION run: | git fetch --tags --force --depth=1 TAG=${GITHUB_REF#refs/tags/} echo "TAG=$TAG" >> $GITHUB_ENV echo "$TAG" > VERSION echo "Building tag: $TAG for ${{ matrix.arch }}"
# - name: Normalize GHCR repository# run: echo "GHCR_REPOSITORY=${GITHUB_REPOSITORY,,}" >> $GITHUB_ENV
- name: Set up Docker Buildx uses: docker/setup-buildx-action@v3
- name: Log in to Docker Hub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }}
# - name: Log in to GHCR# uses: docker/login-action@v3# with:# registry: ghcr.io# username: ${{ github.actor }}# password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (labels) id: meta uses: docker/metadata-action@v5 with: images: | calciumion/new-api# ghcr.io/${{ env.GHCR_REPOSITORY }}
- name: Build & push single-arch (to both registries) uses: docker/build-push-action@v6 with: context: . platforms: ${{ matrix.platform }} push: true tags: | calciumion/new-api:${{ env.TAG }}-${{ matrix.arch }} calciumion/new-api:latest-${{ matrix.arch }}# ghcr.io/${{ env.GHCR_REPOSITORY }}:${{ env.TAG }}-${{ matrix.arch }}# ghcr.io/${{ env.GHCR_REPOSITORY }}:latest-${{ matrix.arch }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max provenance: false sbom: false
create_manifests: name: Create multi-arch manifests (Docker Hub) needs: [build_single_arch] runs-on: ubuntu-latest if: startsWith(github.ref, 'refs/tags/') steps: - name: Extract tag run: echo "TAG=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV## - name: Normalize GHCR repository# run: echo "GHCR_REPOSITORY=${GITHUB_REPOSITORY,,}" >> $GITHUB_ENV
- name: Log in to Docker Hub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Create & push manifest (Docker Hub - version) run: | docker buildx imagetools create \ -t calciumion/new-api:${TAG} \ calciumion/new-api:${TAG}-amd64 \ calciumion/new-api:${TAG}-arm64
- name: Create & push manifest (Docker Hub - latest) run: | docker buildx imagetools create \ -t calciumion/new-api:latest \ calciumion/new-api:latest-amd64 \ calciumion/new-api:latest-arm64
# ---- GHCR ----# - name: Log in to GHCR# uses: docker/login-action@v3# with:# registry: ghcr.io# username: ${{ github.actor }}# password: ${{ secrets.GITHUB_TOKEN }}
# - name: Create & push manifest (GHCR - version)# run: |# docker buildx imagetools create \# -t ghcr.io/${GHCR_REPOSITORY}:${TAG} \# ghcr.io/${GHCR_REPOSITORY}:${TAG}-amd64 \# ghcr.io/${GHCR_REPOSITORY}:${TAG}-arm64## - name: Create & push manifest (GHCR - latest)# run: |# docker buildx imagetools create \# -t ghcr.io/${GHCR_REPOSITORY}:latest \# ghcr.io/${GHCR_REPOSITORY}:latest-amd64 \# ghcr.io/${GHCR_REPOSITORY}:latest-arm64123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141name: Build Electron App
on: push: tags: - '*' # Triggers on version tags like v1.0.0 - '!*-*' # Ignore pre-release tags like v1.0.0-beta - '!*-alpha*' # Ignore alpha tags like v1.0.0-alpha workflow_dispatch: # Allows manual triggering
jobs: build: strategy: matrix: # os: [macos-latest, windows-latest] os: [windows-latest]
runs-on: ${{ matrix.os }} defaults: run: shell: bash
steps: - name: Checkout code uses: actions/checkout@v4 with: fetch-depth: 0
- name: Setup Bun uses: oven-sh/setup-bun@v2 with: bun-version: latest
- name: Setup Node.js uses: actions/setup-node@v4 with: node-version: '20'
- name: Setup Go uses: actions/setup-go@v5 with: go-version: '>=1.25.1'
- name: Build frontend env: CI: "" NODE_OPTIONS: "--max-old-space-size=4096" run: | cd web bun install DISABLE_ESLINT_PLUGIN='true' VITE_REACT_APP_VERSION=$(git describe --tags) bun run build cd ..
# - name: Build Go binary (macos/Linux) # if: runner.os != 'Windows' # run: | # go mod download # go build -ldflags "-s -w -X 'new-api/common.Version=$(git describe --tags)' -extldflags '-static'" -o new-api
- name: Build Go binary (Windows) if: runner.os == 'Windows' run: | go mod download go build -ldflags "-s -w -X 'new-api/common.Version=$(git describe --tags)'" -o new-api.exe
- name: Update Electron version run: | cd electron VERSION=$(git describe --tags) VERSION=${VERSION#v} # Remove 'v' prefix if present # Convert to valid semver: take first 3 components and convert rest to prerelease format # e.g., 0.9.3-patch.1 -> 0.9.3-patch.1 if [[ $VERSION =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)(.*)$ ]]; then MAJOR=${BASH_REMATCH[1]} MINOR=${BASH_REMATCH[2]} PATCH=${BASH_REMATCH[3]} REST=${BASH_REMATCH[4]} VERSION="$MAJOR.$MINOR.$PATCH" # If there's extra content, append it without adding -dev if [[ -n "$REST" ]]; then VERSION="$VERSION$REST" fi fi npm version $VERSION --no-git-tag-version --allow-same-version
- name: Install Electron dependencies run: | cd electron npm install
# - name: Build Electron app (macOS) # if: runner.os == 'macOS' # run: | # cd electron # npm run build:mac # env: # CSC_IDENTITY_AUTO_DISCOVERY: false # Skip code signing
- name: Build Electron app (Windows) if: runner.os == 'Windows' run: | cd electron npm run build:win
# - name: Upload artifacts (macOS) # if: runner.os == 'macOS' # uses: actions/upload-artifact@v4 # with: # name: macos-build # path: | # electron/dist/*.dmg # electron/dist/*.zip
- name: Upload artifacts (Windows) if: runner.os == 'Windows' uses: actions/upload-artifact@v4 with: name: windows-build path: | electron/dist/*.exe
release: needs: build runs-on: ubuntu-latest if: startsWith(github.ref, 'refs/tags/') permissions: contents: write
steps: - name: Download all artifacts uses: actions/download-artifact@v4
- name: Upload to Release uses: softprops/action-gh-release@v2 with: files: | windows-build/* env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142name: Release (Linux, macOS, Windows)permissions: contents: write
on: workflow_dispatch: inputs: name: description: 'reason' required: false push: tags: - '*' - '!*-alpha*'
jobs: linux: name: Linux Release runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Determine Version run: | VERSION=$(git describe --tags) echo "VERSION=$VERSION" >> $GITHUB_ENV - uses: oven-sh/setup-bun@v2 with: bun-version: latest - name: Build Frontend env: CI: "" run: | cd web bun install DISABLE_ESLINT_PLUGIN='true' VITE_REACT_APP_VERSION=$VERSION bun run build cd .. - name: Set up Go uses: actions/setup-go@v3 with: go-version: '>=1.25.1' - name: Build Backend (amd64) run: | go mod download go build -ldflags "-s -w -X 'new-api/common.Version=$VERSION' -extldflags '-static'" -o new-api-$VERSION - name: Build Backend (arm64) run: | sudo apt-get update DEBIAN_FRONTEND=noninteractive sudo apt-get install -y gcc-aarch64-linux-gnu CC=aarch64-linux-gnu-gcc CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -X 'new-api/common.Version=$VERSION' -extldflags '-static'" -o new-api-arm64-$VERSION - name: Release uses: softprops/action-gh-release@v2 if: startsWith(github.ref, 'refs/tags/') with: files: | new-api-* env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
macos: name: macOS Release runs-on: macos-latest steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Determine Version run: | VERSION=$(git describe --tags) echo "VERSION=$VERSION" >> $GITHUB_ENV - uses: oven-sh/setup-bun@v2 with: bun-version: latest - name: Build Frontend env: CI: "" NODE_OPTIONS: "--max-old-space-size=4096" run: | cd web bun install DISABLE_ESLINT_PLUGIN='true' VITE_REACT_APP_VERSION=$VERSION bun run build cd .. - name: Set up Go uses: actions/setup-go@v3 with: go-version: '>=1.25.1' - name: Build Backend run: | go mod download go build -ldflags "-X 'new-api/common.Version=$VERSION'" -o new-api-macos-$VERSION - name: Release uses: softprops/action-gh-release@v2 if: startsWith(github.ref, 'refs/tags/') with: files: new-api-macos-* env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
windows: name: Windows Release runs-on: windows-latest defaults: run: shell: bash steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Determine Version run: | VERSION=$(git describe --tags) echo "VERSION=$VERSION" >> $GITHUB_ENV - uses: oven-sh/setup-bun@v2 with: bun-version: latest - name: Build Frontend env: CI: "" run: | cd web bun install DISABLE_ESLINT_PLUGIN='true' VITE_REACT_APP_VERSION=$VERSION bun run build cd .. - name: Set up Go uses: actions/setup-go@v3 with: go-version: '>=1.25.1' - name: Build Backend run: | go mod download go build -ldflags "-s -w -X 'new-api/common.Version=$VERSION'" -o new-api-$VERSION.exe - name: Release uses: softprops/action-gh-release@v2 if: startsWith(github.ref, 'refs/tags/') with: files: new-api-*.exe env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091name: Sync Release to Gitee
permissions: contents: read
on: workflow_dispatch: inputs: tag_name: description: 'Release Tag to sync (e.g. v1.0.0)' required: true type: string
# 配置你的 Gitee 仓库信息env: GITEE_OWNER: 'QuantumNous' # 修改为你的 Gitee 用户名 GITEE_REPO: 'new-api' # 修改为你的 Gitee 仓库名
jobs: sync-to-gitee: runs-on: sync steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0
- name: Get Release Info id: release_info env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} TAG_NAME: ${{ github.event.inputs.tag_name }} run: | # 获取 release 信息 RELEASE_INFO=$(gh release view "$TAG_NAME" --json name,body,tagName,targetCommitish) RELEASE_NAME=$(echo "$RELEASE_INFO" | jq -r '.name') TARGET_COMMITISH=$(echo "$RELEASE_INFO" | jq -r '.targetCommitish') # 使用多行字符串输出 { echo "release_name=$RELEASE_NAME" echo "target_commitish=$TARGET_COMMITISH" echo "release_body<<EOF" echo "$RELEASE_INFO" | jq -r '.body' echo "EOF" } >> $GITHUB_OUTPUT # 下载 release 的所有附件 gh release download "$TAG_NAME" --dir ./release_assets || echo "No assets to download" # 列出下载的文件 ls -la ./release_assets/ || echo "No assets directory"
- name: Create Gitee Release id: create_release uses: nICEnnnnnnnLee/action-gitee-release@v2.0.0 with: gitee_action: create_release gitee_owner: ${{ env.GITEE_OWNER }} gitee_repo: ${{ env.GITEE_REPO }} gitee_token: ${{ secrets.GITEE_TOKEN }} gitee_tag_name: ${{ github.event.inputs.tag_name }} gitee_release_name: ${{ steps.release_info.outputs.release_name }} gitee_release_body: ${{ steps.release_info.outputs.release_body }} gitee_target_commitish: ${{ steps.release_info.outputs.target_commitish }}
- name: Upload Assets to Gitee if: hashFiles('release_assets/*') != '' uses: nICEnnnnnnnLee/action-gitee-release@v2.0.0 with: gitee_action: upload_asset gitee_owner: ${{ env.GITEE_OWNER }} gitee_repo: ${{ env.GITEE_REPO }} gitee_token: ${{ secrets.GITEE_TOKEN }} gitee_release_id: ${{ steps.create_release.outputs.release-id }} gitee_upload_retry_times: 3 gitee_files: | release_assets/*
- name: Cleanup if: always() run: | rm -rf release_assets/
- name: Summary if: success() run: | echo "✅ Successfully synced release ${{ github.event.inputs.tag_name }} to Gitee!" echo "🔗 Gitee Release URL: https://gitee.com/${{ env.GITEE_OWNER }}/${{ env.GITEE_REPO }}/releases/tag/${{ github.event.inputs.tag_name }}"
1234567891011121314151617181920212223.idea.vscode.zedupload*.exe*.dbbuild*.db-journallogsweb/dist.envone-apinew-api/__debug_bin*.DS_Storetiktoken_cache.eslintcache.gocache.cacheweb/bun.lock
electron/node_moduleselectron/dist1234567891011121314151617181920212223242526272829303132333435363738394041424344FROM oven/bun:latest AS builder
WORKDIR /buildCOPY web/package.json .COPY web/bun.lock .RUN bun installCOPY ./web .COPY ./VERSION .RUN DISABLE_ESLINT_PLUGIN='true' VITE_REACT_APP_VERSION=$(cat VERSION) bun run build
FROM golang:alpine AS builder2ENV GO111MODULE=on CGO_ENABLED=0
ARG TARGETOSARG TARGETARCHENV GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH:-amd64}
WORKDIR /build
ADD go.mod go.sum ./RUN go mod download
COPY . .COPY --from=builder /build/dist ./web/distRUN go build -ldflags "-s -w -X 'github.com/QuantumNous/new-api/common.Version=$(cat VERSION)'" -o new-api
FROM alpine
RUN apk upgrade --no-cache \ && apk add --no-cache ca-certificates tzdata \ && update-ca-certificates
# Create a non-root user for HuggingFace SpacesRUN adduser -D -u 1000 userUSER user
COPY --from=builder2 /build/new-api /new-api
# HuggingFace Spaces requires port 7860ENV PORT=7860EXPOSE 7860
WORKDIR /home/user/dataENTRYPOINT ["/new-api"]1234567891011121314151617181920212223242526272829303132333435363738394041424344FROM oven/bun:latest AS builder
WORKDIR /buildCOPY web/package.json .COPY web/bun.lock .RUN bun installCOPY ./web .COPY ./VERSION .RUN DISABLE_ESLINT_PLUGIN='true' VITE_REACT_APP_VERSION=$(cat VERSION) bun run build
FROM golang:alpine AS builder2ENV GO111MODULE=on CGO_ENABLED=0
ARG TARGETOSARG TARGETARCHENV GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH:-amd64}
WORKDIR /build
ADD go.mod go.sum ./RUN go mod download
COPY . .COPY --from=builder /build/dist ./web/distRUN go build -ldflags "-s -w -X 'github.com/QuantumNous/new-api/common.Version=$(cat VERSION)'" -o new-api
FROM alpine
RUN apk upgrade --no-cache \ && apk add --no-cache ca-certificates tzdata \ && update-ca-certificates
# Create a non-root user for HuggingFace SpacesRUN adduser -D -u 1000 userUSER user
COPY --from=builder2 /build/new-api /new-api
# HuggingFace Spaces requires port 7860ENV PORT=7860EXPOSE 7860
WORKDIR /home/user/dataENTRYPOINT ["/new-api"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103# **New API 许可协议 (Licensing)**
本项目采用**基于使用场景的双重许可 (Usage-Based Dual Licensing)** 模式。
**核心原则:**
- **默认许可:** 本项目默认在 **GNU Affero 通用公共许可证 v3.0 (AGPLv3)** 下提供。任何用户在遵守 AGPLv3 条款和下述附加限制的前提下,均可免费使用。- **商业许可:** 在特定商业场景下,或当您希望获得 AGPLv3 之外的权利时,**必须**获取**商业许可证 (Commercial License)**。
---
## **1. 开源许可证 (Open Source License): AGPLv3 - 适用于基础使用**
- 在遵守 **AGPLv3** 条款的前提下,您可以自由地使用、修改和分发 New API。AGPLv3 的完整文本可以访问 [https://www.gnu.org/licenses/agpl-3.0.html](https://www.gnu.org/licenses/agpl-3.0.html) 获取。- **核心义务:** AGPLv3 的一个关键要求是,如果您修改了 New API 并通过网络提供服务 (SaaS),或者分发了修改后的版本,您必须以 AGPLv3 许可证向所有用户提供相应的**完整源代码**。- **附加限制 (重要):** 在仅使用 AGPLv3 开源许可证的情况下,您**必须**完整保留项目代码中原有的品牌标识、LOGO 及版权声明信息。**禁止以任何形式修改、移除或遮盖**这些信息。如需移除,必须获取商业许可证。- 使用前请务必仔细阅读并理解 AGPLv3 的所有条款及上述附加限制。
## **2. 商业许可证 (Commercial License) - 适用于高级场景及闭源需求**
在以下任一情况下,您**必须**联系我们获取并签署一份商业许可证,才能合法使用 New API:
- **场景一:移除品牌和版权信息** 您希望在您的产品或服务中移除 New API 的 LOGO、UI界面中的版权声明或其他品牌标识。
- **场景二:规避 AGPLv3 开源义务** 您基于 New API 进行了修改,并希望: - 通过网络提供服务(SaaS),但**不希望**向您的服务用户公开您修改后的源代码。 - 分发一个集成了 New API 的软件产品,但**不希望**以 AGPLv3 许可证发布您的产品或公开源代码。
- **场景三:企业政策与集成需求** - 您所在公司的政策、客户合同或项目要求不允许使用 AGPLv3 许可的软件。 - 您需要进行 OEM 集成,将 New API 作为您闭源商业产品的一部分进行再分发。
- **场景四:需要商业支持与保障** 您需要 AGPLv3 未提供的商业保障,如官方技术支持等。
**获取商业许可:** 请通过电子邮件 **support@quantumnous.com** 联系 New API 团队洽谈商业授权事宜。
## **3. 贡献 (Contributions)**
- 我们欢迎社区对 New API 的贡献。所有向本项目提交的贡献(例如通过 Pull Request)都将被视为在 **AGPLv3** 许可证下提供。- 通过向本项目提交贡献,即表示您同意您的代码以 AGPLv3 许可证授权给本项目及所有后续使用者(无论这些使用者最终遵循 AGPLv3 还是商业许可)。- 您也理解并同意,您的贡献可能会被包含在根据商业许可证分发的 New API 版本中。
## **4. 其他条款 (Other Terms)**
- 关于商业许可证的具体条款、条件和价格,以双方签署的正式商业许可协议为准。- 项目维护者保留根据需要更新本许可政策的权利。相关更新将通过项目官方渠道(如代码仓库、官方网站)进行通知。
---
# **New API Licensing**
This project uses a **Usage-Based Dual Licensing** model.
**Core Principles:**
- **Default License:** This project is available by default under the **GNU Affero General Public License v3.0 (AGPLv3)**. Any user may use it free of charge, provided they comply with both the AGPLv3 terms and the additional restrictions listed below.- **Commercial License:** For specific commercial scenarios, or if you require rights beyond those granted by AGPLv3, you **must** obtain a **Commercial License**.
---
## **1. Open Source License: AGPLv3 – For Basic Usage**
- Under the terms of the **AGPLv3**, you are free to use, modify, and distribute New API. The complete AGPLv3 license text can be viewed at [https://www.gnu.org/licenses/agpl-3.0.html](https://www.gnu.org/licenses/agpl-3.0.html).- **Core Obligation:** A key AGPLv3 requirement is that if you modify New API and provide it as a network service (SaaS), or distribute a modified version, you must make the **complete corresponding source code** available to all users under the AGPLv3 license.- **Additional Restriction (Important):** When using only the AGPLv3 open-source license, you **must** retain all original branding, logos, and copyright statements within the project’s code. **You are strictly prohibited from modifying, removing, or concealing** any such information. If you wish to remove this, you must obtain a Commercial License.- Please read and ensure that you fully understand all AGPLv3 terms and the above additional restriction before use.
## **2. Commercial License – For Advanced Scenarios & Closed Source Needs**
You **must** contact us to obtain and sign a Commercial License in any of the following scenarios in order to legally use New API:
- **Scenario 1: Removal of Branding and Copyright** You wish to remove the New API logo, copyright statement, or other branding elements from your product or service.
- **Scenario 2: Avoidance of AGPLv3 Open Source Obligations** You have modified New API and wish to: - Offer it as a network service (SaaS) **without** disclosing your modifications' source code to your users. - Distribute a software product integrated with New API **without** releasing your product under AGPLv3 or open-sourcing the code.
- **Scenario 3: Enterprise Policy & Integration Needs** - Your organization’s policies, client contracts, or project requirements prohibit the use of AGPLv3-licensed software. - You require OEM integration and need to redistribute New API as part of your closed-source commercial product.
- **Scenario 4: Commercial Support and Assurances** You require commercial assurances not provided by AGPLv3, such as official technical support.
**Obtaining a Commercial License:** Please contact the New API team via email at **support@quantumnous.com** to discuss commercial licensing.
## **3. Contributions**
- We welcome community contributions to New API. All contributions (e.g., via Pull Request) are deemed to be provided under the **AGPLv3** license.- By submitting a contribution, you agree that your code is licensed to this project and all downstream users under the AGPLv3 license (regardless of whether those users ultimately operate under AGPLv3 or a Commercial License).- You also acknowledge and agree that your contribution may be included in New API releases distributed under a Commercial License.
## **4. Other Terms**
- The specific terms, conditions, and pricing of the Commercial License are governed by the formal commercial license agreement executed by both parties.- Project maintainers reserve the right to update this licensing policy as needed. Updates will be communicated via official project channels (e.g., repository, official website).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447<div align="center">

# New API
🍥 **Next-Generation Large Model Gateway and AI Asset Management System**
<p align="center"> <a href="./README.md">中文</a> | <strong>English</strong> | <a href="./README.fr.md">Français</a> | <a href="./README.ja.md">日本語</a></p>
<p align="center"> <a href="https://raw.githubusercontent.com/Calcium-Ion/new-api/main/LICENSE"> <img src="https://img.shields.io/github/license/Calcium-Ion/new-api?color=brightgreen" alt="license"> </a> <a href="https://github.com/Calcium-Ion/new-api/releases/latest"> <img src="https://img.shields.io/github/v/release/Calcium-Ion/new-api?color=brightgreen&include_prereleases" alt="release"> </a> <a href="https://github.com/users/Calcium-Ion/packages/container/package/new-api"> <img src="https://img.shields.io/badge/docker-ghcr.io-blue" alt="docker"> </a> <a href="https://hub.docker.com/r/CalciumIon/new-api"> <img src="https://img.shields.io/badge/docker-dockerHub-blue" alt="docker"> </a> <a href="https://goreportcard.com/report/github.com/Calcium-Ion/new-api"> <img src="https://goreportcard.com/badge/github.com/Calcium-Ion/new-api" alt="GoReportCard"> </a></p>
<p align="center"> <a href="https://trendshift.io/repositories/8227" target="_blank"> <img src="https://trendshift.io/api/badge/repositories/8227" alt="Calcium-Ion%2Fnew-api | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/> </a></p>
<p align="center"> <a href="#-quick-start">Quick Start</a> • <a href="#-key-features">Key Features</a> • <a href="#-deployment">Deployment</a> • <a href="#-documentation">Documentation</a> • <a href="#-help-support">Help</a></p>
</div>
## 📝 Project Description
> [!NOTE] > This is an open-source project developed based on [One API](https://github.com/songquanpeng/one-api)
> [!IMPORTANT] > - This project is for personal learning purposes only, with no guarantee of stability or technical support> - Users must comply with OpenAI's [Terms of Use](https://openai.com/policies/terms-of-use) and **applicable laws and regulations**, and must not use it for illegal purposes> - According to the [《Interim Measures for the Management of Generative Artificial Intelligence Services》](http://www.cac.gov.cn/2023-07/13/c_1690898327029107.htm), please do not provide any unregistered generative AI services to the public in China.
---
## 🤝 Trusted Partners
<p align="center"> <em>No particular order</em></p>
<p align="center"> <a href="https://www.cherry-ai.com/" target="_blank"> <img src="./docs/images/cherry-studio.png" alt="Cherry Studio" height="80" /> </a> <a href="https://bda.pku.edu.cn/" target="_blank"> <img src="./docs/images/pku.png" alt="Peking University" height="80" /> </a> <a href="https://www.compshare.cn/?ytag=GPU_yy_gh_newapi" target="_blank"> <img src="./docs/images/ucloud.png" alt="UCloud" height="80" /> </a> <a href="https://www.aliyun.com/" target="_blank"> <img src="./docs/images/aliyun.png" alt="Alibaba Cloud" height="80" /> </a> <a href="https://io.net/" target="_blank"> <img src="./docs/images/io-net.png" alt="IO.NET" height="80" /> </a></p>
---
## 🙏 Special Thanks
<p align="center"> <a href="https://www.jetbrains.com/?from=new-api" target="_blank"> <img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="JetBrains Logo" width="120" /> </a></p>
<p align="center"> <strong>Thanks to <a href="https://www.jetbrains.com/?from=new-api">JetBrains</a> for providing free open-source development license for this project</strong></p>
---
## 🚀 Quick Start
### Using Docker Compose (Recommended)
```bash# Clone the projectgit clone https://github.com/QuantumNous/new-api.gitcd new-api
# Edit docker-compose.yml configurationnano docker-compose.yml
# Start the servicedocker-compose up -d```
<details><summary><strong>Using Docker Commands</strong></summary>
```bash# Pull the latest imagedocker pull calciumion/new-api:latest
# Using SQLite (default)docker run --name new-api -d --restart always \ -p 3000:3000 \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest
# Using MySQLdocker run --name new-api -d --restart always \ -p 3000:3000 \ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
> **💡 Tip:** `-v ./data:/data` will save data in the `data` folder of the current directory, you can also change it to an absolute path like `-v /your/custom/path:/data`
</details>
---
🎉 After deployment is complete, visit `http://localhost:3000` to start using!
📖 For more deployment methods, please refer to [Deployment Guide](https://docs.newapi.pro/installation)
---
## 📚 Documentation
<div align="center">
### 📖 [Official Documentation](https://docs.newapi.pro/) | [](https://deepwiki.com/QuantumNous/new-api)
</div>
**Quick Navigation:**
| Category | Link ||------|------|| 🚀 Deployment Guide | [Installation Documentation](https://docs.newapi.pro/installation) || ⚙️ Environment Configuration | [Environment Variables](https://docs.newapi.pro/installation/environment-variables) || 📡 API Documentation | [API Documentation](https://docs.newapi.pro/api) || ❓ FAQ | [FAQ](https://docs.newapi.pro/support/faq) || 💬 Community Interaction | [Communication Channels](https://docs.newapi.pro/support/community-interaction) |
---
## ✨ Key Features
> For detailed features, please refer to [Features Introduction](https://docs.newapi.pro/wiki/features-introduction)
### 🎨 Core Functions
| Feature | Description ||------|------|| 🎨 New UI | Modern user interface design || 🌍 Multi-language | Supports Chinese, English, French, Japanese || 🔄 Data Compatibility | Fully compatible with the original One API database || 📈 Data Dashboard | Visual console and statistical analysis || 🔒 Permission Management | Token grouping, model restrictions, user management |
### 💰 Payment and Billing
- ✅ Online recharge (EPay, Stripe)- ✅ Pay-per-use model pricing- ✅ Cache billing support (OpenAI, Azure, DeepSeek, Claude, Qwen and all supported models)- ✅ Flexible billing policy configuration
### 🔐 Authorization and Security
- 😈 Discord authorization login- 🤖 LinuxDO authorization login- 📱 Telegram authorization login- 🔑 OIDC unified authentication
### 🚀 Advanced Features
**API Format Support:**- ⚡ [OpenAI Responses](https://docs.newapi.pro/api/openai-responses)- ⚡ [OpenAI Realtime API](https://docs.newapi.pro/api/openai-realtime) (including Azure)- ⚡ [Claude Messages](https://docs.newapi.pro/api/anthropic-chat)- ⚡ [Google Gemini](https://docs.newapi.pro/api/google-gemini-chat/)- 🔄 [Rerank Models](https://docs.newapi.pro/api/jinaai-rerank) (Cohere, Jina)
**Intelligent Routing:**- ⚖️ Channel weighted random- 🔄 Automatic retry on failure- 🚦 User-level model rate limiting
**Format Conversion:**- 🔄 OpenAI ⇄ Claude Messages- 🔄 OpenAI ⇄ Gemini Chat- 🔄 Thinking-to-content functionality
**Reasoning Effort Support:**
<details><summary>View detailed configuration</summary>
**OpenAI series models:**- `o3-mini-high` - High reasoning effort- `o3-mini-medium` - Medium reasoning effort- `o3-mini-low` - Low reasoning effort- `gpt-5-high` - High reasoning effort- `gpt-5-medium` - Medium reasoning effort- `gpt-5-low` - Low reasoning effort
**Claude thinking models:**- `claude-3-7-sonnet-20250219-thinking` - Enable thinking mode
**Google Gemini series models:**- `gemini-2.5-flash-thinking` - Enable thinking mode- `gemini-2.5-flash-nothinking` - Disable thinking mode- `gemini-2.5-pro-thinking` - Enable thinking mode- `gemini-2.5-pro-thinking-128` - Enable thinking mode with thinking budget of 128 tokens
</details>
---
## 🤖 Model Support
> For details, please refer to [API Documentation - Relay Interface](https://docs.newapi.pro/api)
| Model Type | Description | Documentation ||---------|------|------|| 🤖 OpenAI GPTs | gpt-4-gizmo-* series | - || 🎨 Midjourney-Proxy | [Midjourney-Proxy(Plus)](https://github.com/novicezk/midjourney-proxy) | [Documentation](https://docs.newapi.pro/api/midjourney-proxy-image) || 🎵 Suno-API | [Suno API](https://github.com/Suno-API/Suno-API) | [Documentation](https://docs.newapi.pro/api/suno-music) || 🔄 Rerank | Cohere, Jina | [Documentation](https://docs.newapi.pro/api/jinaai-rerank) || 💬 Claude | Messages format | [Documentation](https://docs.newapi.pro/api/anthropic-chat) || 🌐 Gemini | Google Gemini format | [Documentation](https://docs.newapi.pro/api/google-gemini-chat/) || 🔧 Dify | ChatFlow mode | - || 🎯 Custom | Supports complete call address | - |
### 📡 Supported Interfaces
<details><summary>View complete interface list</summary>
- [Chat Interface (Chat Completions)](https://docs.newapi.pro/api/openai-chat)- [Response Interface (Responses)](https://docs.newapi.pro/api/openai-responses)- [Image Interface (Image)](https://docs.newapi.pro/api/openai-image)- [Audio Interface (Audio)](https://docs.newapi.pro/api/openai-audio)- [Video Interface (Video)](https://docs.newapi.pro/api/openai-video)- [Embedding Interface (Embeddings)](https://docs.newapi.pro/api/openai-embeddings)- [Rerank Interface (Rerank)](https://docs.newapi.pro/api/jinaai-rerank)- [Realtime Conversation (Realtime)](https://docs.newapi.pro/api/openai-realtime)- [Claude Chat](https://docs.newapi.pro/api/anthropic-chat)- [Google Gemini Chat](https://docs.newapi.pro/api/google-gemini-chat/)
</details>
---
## 🚢 Deployment
> [!TIP]> **Latest Docker image:** `calciumion/new-api:latest`
### 📋 Deployment Requirements
| Component | Requirement ||------|------|| **Local database** | SQLite (Docker must mount `/data` directory)|| **Remote database** | MySQL ≥ 5.7.8 or PostgreSQL ≥ 9.6 || **Container engine** | Docker / Docker Compose |
### ⚙️ Environment Variable Configuration
<details><summary>Common environment variable configuration</summary>
| Variable Name | Description | Default Value ||--------|------|--------|| `SESSION_SECRET` | Session secret (required for multi-machine deployment) | - || `CRYPTO_SECRET` | Encryption secret (required for Redis) | - || `SQL_DSN` | Database connection string | - || `REDIS_CONN_STRING` | Redis connection string | - || `STREAMING_TIMEOUT` | Streaming timeout (seconds) | `300` || `AZURE_DEFAULT_API_VERSION` | Azure API version | `2025-04-01-preview` || `ERROR_LOG_ENABLED` | Error log switch | `false` |
📖 **Complete configuration:** [Environment Variables Documentation](https://docs.newapi.pro/installation/environment-variables)
</details>
### 🔧 Deployment Methods
<details><summary><strong>Method 1: Docker Compose (Recommended)</strong></summary>
```bash# Clone the projectgit clone https://github.com/QuantumNous/new-api.gitcd new-api
# Edit configurationnano docker-compose.yml
# Start servicedocker-compose up -d```
</details>
<details><summary><strong>Method 2: Docker Commands</strong></summary>
**Using SQLite:**```bashdocker run --name new-api -d --restart always \ -p 3000:3000 \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
**Using MySQL:**```bashdocker run --name new-api -d --restart always \ -p 3000:3000 \ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
> **💡 Path explanation:** > - `./data:/data` - Relative path, data saved in the data folder of the current directory> - You can also use absolute path, e.g.: `/your/custom/path:/data`
</details>
<details><summary><strong>Method 3: BaoTa Panel</strong></summary>
1. Install BaoTa Panel (≥ 9.2.0 version)2. Search for **New-API** in the application store3. One-click installation
📖 [Tutorial with images](./docs/BT.md)
</details>
### ⚠️ Multi-machine Deployment Considerations
> [!WARNING]> - **Must set** `SESSION_SECRET` - Otherwise login status inconsistent> - **Shared Redis must set** `CRYPTO_SECRET` - Otherwise data cannot be decrypted
### 🔄 Channel Retry and Cache
**Retry configuration:** `Settings → Operation Settings → General Settings → Failure Retry Count`
**Cache configuration:**- `REDIS_CONN_STRING`: Redis cache (recommended)- `MEMORY_CACHE_ENABLED`: Memory cache
---
## 🔗 Related Projects
### Upstream Projects
| Project | Description ||------|------|| [One API](https://github.com/songquanpeng/one-api) | Original project base || [Midjourney-Proxy](https://github.com/novicezk/midjourney-proxy) | Midjourney interface support |
### Supporting Tools
| Project | Description ||------|------|| [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool) | Key quota query tool || [new-api-horizon](https://github.com/Calcium-Ion/new-api-horizon) | New API high-performance optimized version |
---
## 💬 Help Support
### 📖 Documentation Resources
| Resource | Link ||------|------|| 📘 FAQ | [FAQ](https://docs.newapi.pro/support/faq) || 💬 Community Interaction | [Communication Channels](https://docs.newapi.pro/support/community-interaction) || 🐛 Issue Feedback | [Issue Feedback](https://docs.newapi.pro/support/feedback-issues) || 📚 Complete Documentation | [Official Documentation](https://docs.newapi.pro/support) |
### 🤝 Contribution Guide
Welcome all forms of contribution!
- 🐛 Report Bugs- 💡 Propose New Features- 📝 Improve Documentation- 🔧 Submit Code
---
## 🌟 Star History
<div align="center">
[](https://star-history.com/#Calcium-Ion/new-api&Date)
</div>
---
<div align="center">
### 💖 Thank you for using New API
If this project is helpful to you, welcome to give us a ⭐️ Star!
**[Official Documentation](https://docs.newapi.pro/)** • **[Issue Feedback](https://github.com/Calcium-Ion/new-api/issues)** • **[Latest Release](https://github.com/Calcium-Ion/new-api/releases)**
<sub>Built with ❤️ by QuantumNous</sub>
</div>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441<div align="center">

# New API
🍥 **Passerelle de modèles étendus de nouvelle génération et système de gestion d'actifs d'IA**
<p align="center"> <a href="./README.md">中文</a> | <a href="./README.en.md">English</a> | <strong>Français</strong> | <a href="./README.ja.md">日本語</a></p>
<p align="center"> <a href="https://raw.githubusercontent.com/Calcium-Ion/new-api/main/LICENSE"> <img src="https://img.shields.io/github/license/Calcium-Ion/new-api?color=brightgreen" alt="licence"> </a> <a href="https://github.com/Calcium-Ion/new-api/releases/latest"> <img src="https://img.shields.io/github/v/release/Calcium-Ion/new-api?color=brightgreen&include_prereleases" alt="version"> </a> <a href="https://github.com/users/Calcium-Ion/packages/container/package/new-api"> <img src="https://img.shields.io/badge/docker-ghcr.io-blue" alt="docker"> </a> <a href="https://hub.docker.com/r/CalciumIon/new-api"> <img src="https://img.shields.io/badge/docker-dockerHub-blue" alt="docker"> </a> <a href="https://goreportcard.com/report/github.com/Calcium-Ion/new-api"> <img src="https://goreportcard.com/badge/github.com/Calcium-Ion/new-api" alt="GoReportCard"> </a></p>
<p align="center"> <a href="https://trendshift.io/repositories/8227" target="_blank"> <img src="https://trendshift.io/api/badge/repositories/8227" alt="Calcium-Ion%2Fnew-api | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/> </a></p>
<p align="center"> <a href="#-démarrage-rapide">Démarrage rapide</a> • <a href="#-fonctionnalités-clés">Fonctionnalités clés</a> • <a href="#-déploiement">Déploiement</a> • <a href="#-documentation">Documentation</a> • <a href="#-aide-support">Aide</a></p>
</div>
## 📝 Description du projet
> [!NOTE] > Il s'agit d'un projet open-source développé sur la base de [One API](https://github.com/songquanpeng/one-api)
> [!IMPORTANT] > - Ce projet est uniquement destiné à des fins d'apprentissage personnel, sans garantie de stabilité ni de support technique.> - Les utilisateurs doivent se conformer aux [Conditions d'utilisation](https://openai.com/policies/terms-of-use) d'OpenAI et aux **lois et réglementations applicables**, et ne doivent pas l'utiliser à des fins illégales.> - Conformément aux [《Mesures provisoires pour la gestion des services d'intelligence artificielle générative》](http://www.cac.gov.cn/2023-07/13/c_1690898327029107.htm), veuillez ne fournir aucun service d'IA générative non enregistré au public en Chine.
---
## 🤝 Partenaires de confiance
<p align="center"> <em>Sans ordre particulier</em></p>
<p align="center"> <a href="https://www.cherry-ai.com/" target="_blank"> <img src="./docs/images/cherry-studio.png" alt="Cherry Studio" height="80" /> </a> <a href="https://bda.pku.edu.cn/" target="_blank"> <img src="./docs/images/pku.png" alt="Université de Pékin" height="80" /> </a> <a href="https://www.compshare.cn/?ytag=GPU_yy_gh_newapi" target="_blank"> <img src="./docs/images/ucloud.png" alt="UCloud" height="80" /> </a> <a href="https://www.aliyun.com/" target="_blank"> <img src="./docs/images/aliyun.png" alt="Alibaba Cloud" height="80" /> </a> <a href="https://io.net/" target="_blank"> <img src="./docs/images/io-net.png" alt="IO.NET" height="80" /> </a></p>
---
## 🙏 Remerciements spéciaux
<p align="center"> <a href="https://www.jetbrains.com/?from=new-api" target="_blank"> <img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="JetBrains Logo" width="120" /> </a></p>
<p align="center"> <strong>Merci à <a href="https://www.jetbrains.com/?from=new-api">JetBrains</a> pour avoir fourni une licence de développement open-source gratuite pour ce projet</strong></p>
---
## 🚀 Démarrage rapide
### Utilisation de Docker Compose (recommandé)
```bash# Cloner le projetgit clone https://github.com/QuantumNous/new-api.gitcd new-api
# Modifier la configuration docker-compose.ymlnano docker-compose.yml
# Démarrer le servicedocker-compose up -d```
<details><summary><strong>Utilisation des commandes Docker</strong></summary>
```bash# Tirer la dernière imagedocker pull calciumion/new-api:latest
# Utilisation de SQLite (par défaut)docker run --name new-api -d --restart always \ -p 3000:3000 \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest
# Utilisation de MySQLdocker run --name new-api -d --restart always \ -p 3000:3000 \ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
> **💡 Astuce:** `-v ./data:/data` sauvegardera les données dans le dossier `data` du répertoire actuel, vous pouvez également le changer en chemin absolu comme `-v /your/custom/path:/data`
</details>
---
🎉 Après le déploiement, visitez `http://localhost:3000` pour commencer à utiliser!
📖 Pour plus de méthodes de déploiement, veuillez vous référer à [Guide de déploiement](https://docs.newapi.pro/installation)
---
## 📚 Documentation
<div align="center">
### 📖 [Documentation officielle](https://docs.newapi.pro/) | [](https://deepwiki.com/QuantumNous/new-api)
</div>
**Navigation rapide:**
| Catégorie | Lien ||------|------|| 🚀 Guide de déploiement | [Documentation d'installation](https://docs.newapi.pro/installation) || ⚙️ Configuration de l'environnement | [Variables d'environnement](https://docs.newapi.pro/installation/environment-variables) || 📡 Documentation de l'API | [Documentation de l'API](https://docs.newapi.pro/api) || ❓ FAQ | [FAQ](https://docs.newapi.pro/support/faq) || 💬 Interaction avec la communauté | [Canaux de communication](https://docs.newapi.pro/support/community-interaction) |
---
## ✨ Fonctionnalités clés
> Pour les fonctionnalités détaillées, veuillez vous référer à [Présentation des fonctionnalités](https://docs.newapi.pro/wiki/features-introduction) |
### 🎨 Fonctions principales
| Fonctionnalité | Description ||------|------|| 🎨 Nouvelle interface utilisateur | Conception d'interface utilisateur moderne || 🌍 Multilingue | Prend en charge le chinois, l'anglais, le français, le japonais || 🔄 Compatibilité des données | Complètement compatible avec la base de données originale de One API || 📈 Tableau de bord des données | Console visuelle et analyse statistique || 🔒 Gestion des permissions | Regroupement de jetons, restrictions de modèles, gestion des utilisateurs |
### 💰 Paiement et facturation
- ✅ Recharge en ligne (EPay, Stripe)- ✅ Tarification des modèles de paiement à l'utilisation- ✅ Prise en charge de la facturation du cache (OpenAI, Azure, DeepSeek, Claude, Qwen et tous les modèles pris en charge)- ✅ Configuration flexible des politiques de facturation
### 🔐 Autorisation et sécurité
- 🤖 Connexion par autorisation LinuxDO- 📱 Connexion par autorisation Telegram- 🔑 Authentification unifiée OIDC
### 🚀 Fonctionnalités avancées
**Prise en charge des formats d'API:**- ⚡ [OpenAI Responses](https://docs.newapi.pro/api/openai-responses)- ⚡ [OpenAI Realtime API](https://docs.newapi.pro/api/openai-realtime) (y compris Azure)- ⚡ [Claude Messages](https://docs.newapi.pro/api/anthropic-chat)- ⚡ [Google Gemini](https://docs.newapi.pro/api/google-gemini-chat/)- 🔄 [Modèles Rerank](https://docs.newapi.pro/api/jinaai-rerank) (Cohere, Jina)
**Routage intelligent:**- ⚖️ Sélection aléatoire pondérée des canaux- 🔄 Nouvelle tentative automatique en cas d'échec- 🚦 Limitation du débit du modèle pour les utilisateurs
**Conversion de format:**- 🔄 OpenAI ⇄ Claude Messages- 🔄 OpenAI ⇄ Gemini Chat- 🔄 Fonctionnalité de la pensée au contenu
**Prise en charge de l'effort de raisonnement:**
<details><summary>Voir la configuration détaillée</summary>
**Modèles de la série o d'OpenAI:**- `o3-mini-high` - Effort de raisonnement élevé- `o3-mini-medium` - Effort de raisonnement moyen- `o3-mini-low` - Effort de raisonnement faible
**Modèles de pensée de Claude:**- `claude-3-7-sonnet-20250219-thinking` - Activer le mode de pensée
**Modèles de la série Google Gemini:**- `gemini-2.5-flash-thinking` - Activer le mode de pensée- `gemini-2.5-flash-nothinking` - Désactiver le mode de pensée- `gemini-2.5-pro-thinking` - Activer le mode de pensée- `gemini-2.5-pro-thinking-128` - Activer le mode de pensée avec budget de pensée de 128 tokens
</details>
---
## 🤖 Prise en charge des modèles
> Pour les détails, veuillez vous référer à [Documentation de l'API - Interface de relais](https://docs.newapi.pro/api)
| Type de modèle | Description | Documentation ||---------|------|------|| 🤖 OpenAI GPTs | série gpt-4-gizmo-* | - || 🎨 Midjourney-Proxy | [Midjourney-Proxy(Plus)](https://github.com/novicezk/midjourney-proxy) | [Documentation](https://docs.newapi.pro/api/midjourney-proxy-image) || 🎵 Suno-API | [Suno API](https://github.com/Suno-API/Suno-API) | [Documentation](https://docs.newapi.pro/api/suno-music) || 🔄 Rerank | Cohere, Jina | [Documentation](https://docs.newapi.pro/api/jinaai-rerank) || 💬 Claude | Format Messages | [Documentation](https://docs.newapi.pro/api/anthropic-chat) || 🌐 Gemini | Format Google Gemini | [Documentation](https://docs.newapi.pro/api/google-gemini-chat/) || 🔧 Dify | Mode ChatFlow | - || 🎯 Personnalisé | Prise en charge de l'adresse d'appel complète | - |
### 📡 Interfaces prises en charge
<details><summary>Voir la liste complète des interfaces</summary>
- [Interface de discussion (Chat Completions)](https://docs.newapi.pro/api/openai-chat)- [Interface de réponse (Responses)](https://docs.newapi.pro/api/openai-responses)- [Interface d'image (Image)](https://docs.newapi.pro/api/openai-image)- [Interface audio (Audio)](https://docs.newapi.pro/api/openai-audio)- [Interface vidéo (Video)](https://docs.newapi.pro/api/openai-video)- [Interface d'incorporation (Embeddings)](https://docs.newapi.pro/api/openai-embeddings)- [Interface de rerank (Rerank)](https://docs.newapi.pro/api/jinaai-rerank)- [Conversation en temps réel (Realtime)](https://docs.newapi.pro/api/openai-realtime)- [Discussion Claude](https://docs.newapi.pro/api/anthropic-chat)- [Discussion Google Gemini](https://docs.newapi.pro/api/google-gemini-chat/)
</details>
---
## 🚢 Déploiement
> [!TIP]> **Dernière image Docker:** `calciumion/new-api:latest`
### 📋 Exigences de déploiement
| Composant | Exigence ||------|------|| **Base de données locale** | SQLite (Docker doit monter le répertoire `/data`)|| **Base de données distante | MySQL ≥ 5.7.8 ou PostgreSQL ≥ 9.6 || **Moteur de conteneur** | Docker / Docker Compose |
### ⚙️ Configuration des variables d'environnement
<details><summary>Configuration courante des variables d'environnement</summary>
| Nom de variable | Description | Valeur par défaut ||--------|------|--------|| `SESSION_SECRET` | Secret de session (requis pour le déploiement multi-machines) || `CRYPTO_SECRET` | Secret de chiffrement (requis pour Redis) | - || `SQL_DSN` | Chaine de connexion à la base de données | - || `REDIS_CONN_STRING` | Chaine de connexion Redis | - || `STREAMING_TIMEOUT` | Délai d'expiration du streaming (secondes) | `300` || `AZURE_DEFAULT_API_VERSION` | Version de l'API Azure | `2025-04-01-preview` || `ERROR_LOG_ENABLED` | Interrupteur du journal d'erreurs | `false` |
📖 **Configuration complète:** [Documentation des variables d'environnement](https://docs.newapi.pro/installation/environment-variables)
</details>
### 🔧 Méthodes de déploiement
<details><summary><strong>Méthode 1: Docker Compose (recommandé)</strong></summary>
```bash# Cloner le projetgit clone https://github.com/QuantumNous/new-api.gitcd new-api
# Modifier la configurationnano docker-compose.yml
# Démarrer le servicedocker-compose up -d```
</details>
<details><summary><strong>Méthode 2: Commandes Docker</strong></summary>
**Utilisation de SQLite:**```bashdocker run --name new-api -d --restart always \ -p 3000:3000 \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
**Utilisation de MySQL:**```bashdocker run --name new-api -d --restart always \ -p 3000:3000 \ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
> **💡 Explication du chemin:** > - `./data:/data` - Chemin relatif, données sauvegardées dans le dossier data du répertoire actuel> - Vous pouvez également utiliser un chemin absolu, par exemple : `/your/custom/path:/data`
</details>
<details><summary><strong>Méthode 3: Panneau BaoTa</strong></summary>
1. Installez le panneau BaoTa (version **9.2.0** ou supérieure), recherchez **New-API** dans le magasin d'applications et installez-le.2. Recherchez **New-API** dans le magasin d'applications et installez-le.
📖 [Tutoriel avec des images](./docs/BT.md)
</details>
### ⚠️ Considérations sur le déploiement multi-machines
> [!WARNING]> - **Doit définir** `SESSION_SECRET` - Sinon l'état de connexion sera incohérent sur plusieurs machines> - **Redis partagé doit définir** `CRYPTO_SECRET` - Sinon les données ne pourront pas être déchiffrées
### 🔄 Nouvelle tentative de canal et cache
**Configuration de la nouvelle tentative:** `Paramètres → Paramètres de fonctionnement → Paramètres généraux → Nombre de tentatives en cas d'échec`
**Configuration du cache:**- `REDIS_CONN_STRING`: Cache Redis (recommandé)- `MEMORY_CACHE_ENABLED`: Cache mémoire
---
## 🔗 Projets connexes
### Projets en amont
| Projet | Description ||------|------|| [One API](https://github.com/songquanpeng/one-api) | Base du projet original || [Midjourney-Proxy](https://github.com/novicezk/midjourney-proxy) | Prise en charge de l'interface Midjourney |
### Outils d'accompagnement
| Projet | Description ||------|------|| [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool) | Outil de recherche de quota d'utilisation avec une clé |
---
## 💬 Aide et support
### 📖 Ressources de documentation
| Ressource | Lien ||------|------|| 📘 FAQ | [FAQ](https://docs.newapi.pro/support/faq) || 💬 Interaction avec la communauté | [Canaux de communication](https://docs.newapi.pro/support/community-interaction) || 🐛 Commentaires sur les problèmes | [Commentaires sur les problèmes](https://docs.newapi.pro/support/feedback-issues) || 📚 Documentation complète | [Documentation officielle](https://docs.newapi.pro/support) |
### 🤝 Guide de contribution
Bienvenue à toutes les formes de contribution!
- 🐛 Signaler des bogues- 💡 Proposer de nouvelles fonctionnalités- 📝 Améliorer la documentation- 🔧 Soumettre du code
---
## 🌟 Historique des étoiles
<div align="center">
[](https://star-history.com/#Calcium-Ion/new-api&Date)
</div>
---
<div align="center">
### 💖 Merci d'utiliser New API
Si ce projet vous est utile, bienvenue à nous donner une ⭐️ Étoile!
**[Documentation officielle](https://docs.newapi.pro/)** • **[Commentaires sur les problèmes](https://github.com/Calcium-Ion/new-api/issues)** • **[Dernière version](https://github.com/Calcium-Ion/new-api/releases)**
<sub>Construit avec ❤️ par QuantumNous</sub>
</div>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450<div align="center">

# New API
🍥 **次世代大規模モデルゲートウェイとAI資産管理システム**
<p align="center"> <a href="./README.md">中文</a> | <a href="./README.en.md">English</a> | <a href="./README.fr.md">Français</a> | <strong>日本語</strong></p>
<p align="center"> <a href="https://raw.githubusercontent.com/Calcium-Ion/new-api/main/LICENSE"> <img src="https://img.shields.io/github/license/Calcium-Ion/new-api?color=brightgreen" alt="license"> </a> <a href="https://github.com/Calcium-Ion/new-api/releases/latest"> <img src="https://img.shields.io/github/v/release/Calcium-Ion/new-api?color=brightgreen&include_prereleases" alt="release"> </a> <a href="https://github.com/users/Calcium-Ion/packages/container/package/new-api"> <img src="https://img.shields.io/badge/docker-ghcr.io-blue" alt="docker"> </a> <a href="https://hub.docker.com/r/CalciumIon/new-api"> <img src="https://img.shields.io/badge/docker-dockerHub-blue" alt="docker"> </a> <a href="https://goreportcard.com/report/github.com/Calcium-Ion/new-api"> <img src="https://goreportcard.com/badge/github.com/Calcium-Ion/new-api" alt="GoReportCard"> </a></p>
<p align="center"> <a href="https://trendshift.io/repositories/8227" target="_blank"> <img src="https://trendshift.io/api/badge/repositories/8227" alt="Calcium-Ion%2Fnew-api | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/> </a></p>
<p align="center"> <a href="#-クイックスタート">クイックスタート</a> • <a href="#-主な機能">主な機能</a> • <a href="#-デプロイ">デプロイ</a> • <a href="#-ドキュメント">ドキュメント</a> • <a href="#-ヘルプサポート">ヘルプ</a></p>
</div>
## 📝 プロジェクト説明
> [!NOTE] > 本プロジェクトは、[One API](https://github.com/songquanpeng/one-api)をベースに二次開発されたオープンソースプロジェクトです
> [!IMPORTANT] > - 本プロジェクトは個人学習用のみであり、安定性の保証や技術サポートは提供しません。> - ユーザーは、OpenAIの[利用規約](https://openai.com/policies/terms-of-use)および**法律法規**を遵守する必要があり、違法な目的で使用してはいけません。> - [《生成式人工智能服务管理暂行办法》](http://www.cac.gov.cn/2023-07/13/c_1690898327029107.htm)の要求に従い、中国地域の公衆に未登録の生成式AI サービスを提供しないでください。
---
## 🤝 信頼できるパートナー
<p align="center"> <em>順不同</em></p>
<p align="center"> <a href="https://www.cherry-ai.com/" target="_blank"> <img src="./docs/images/cherry-studio.png" alt="Cherry Studio" height="80" /> </a> <a href="https://bda.pku.edu.cn/" target="_blank"> <img src="./docs/images/pku.png" alt="北京大学" height="80" /> </a> <a href="https://www.compshare.cn/?ytag=GPU_yy_gh_newapi" target="_blank"> <img src="./docs/images/ucloud.png" alt="UCloud 優刻得" height="80" /> </a> <a href="https://www.aliyun.com/" target="_blank"> <img src="./docs/images/aliyun.png" alt="Alibaba Cloud" height="80" /> </a> <a href="https://io.net/" target="_blank"> <img src="./docs/images/io-net.png" alt="IO.NET" height="80" /> </a></p>
---
## 🙏 特別な感謝
<p align="center"> <a href="https://www.jetbrains.com/?from=new-api" target="_blank"> <img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="JetBrains Logo" width="120" /> </a></p>
<p align="center"> <strong>感謝 <a href="https://www.jetbrains.com/?from=new-api">JetBrains</a> が本プロジェクトに無料のオープンソース開発ライセンスを提供してくれたことに感謝します</strong></p>
---
## 🚀 クイックスタート
### Docker Composeを使用(推奨)
```bash# プロジェクトをクローンgit clone https://github.com/QuantumNous/new-api.gitcd new-api
# docker-compose.yml 設定を編集nano docker-compose.yml
# サービスを起動docker-compose up -d```
<details><summary><strong>Dockerコマンドを使用</strong></summary>
```bash# 最新のイメージをプルdocker pull calciumion/new-api:latest
# SQLiteを使用(デフォルト)docker run --name new-api -d --restart always \ -p 3000:3000 \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest
# MySQLを使用docker run --name new-api -d --restart always \ -p 3000:3000 \ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
> **💡 ヒント:** `-v ./data:/data` は現在のディレクトリの `data` フォルダにデータを保存します。絶対パスに変更することもできます:`-v /your/custom/path:/data`
</details>
---
🎉 デプロイが完了したら、`http://localhost:3000` にアクセスして使用を開始してください!
📖 その他のデプロイ方法については[デプロイガイド](https://docs.newapi.pro/installation)を参照してください。
---
## 📚 ドキュメント
<div align="center">
### 📖 [公式ドキュメント](https://docs.newapi.pro/) | [](https://deepwiki.com/QuantumNous/new-api)
</div>
**クイックナビゲーション:**
| カテゴリ | リンク ||------|------|| 🚀 デプロイガイド | [インストールドキュメント](https://docs.newapi.pro/installation) || ⚙️ 環境設定 | [環境変数](https://docs.newapi.pro/installation/environment-variables) || 📡 APIドキュメント | [APIドキュメント](https://docs.newapi.pro/api) || ❓ よくある質問 | [FAQ](https://docs.newapi.pro/support/faq) || 💬 コミュニティ交流 | [交流チャネル](https://docs.newapi.pro/support/community-interaction) |
---
## ✨ 主な機能
> 詳細な機能については[機能説明](https://docs.newapi.pro/wiki/features-introduction)を参照してください。
### 🎨 コア機能
| 機能 | 説明 ||------|------|| 🎨 新しいUI | モダンなユーザーインターフェースデザイン || 🌍 多言語 | 中国語、英語、フランス語、日本語をサポート || 🔄 データ互換性 | オリジナルのOne APIデータベースと完全に互換性あり || 📈 データダッシュボード | ビジュアルコンソールと統計分析 || 🔒 権限管理 | トークングループ化、モデル制限、ユーザー管理 |
### 💰 支払いと課金
- ✅ オンライン充電(EPay、Stripe)- ✅ モデルの従量課金- ✅ キャッシュ課金サポート(OpenAI、Azure、DeepSeek、Claude、Qwenなどすべてのサポートされているモデル)- ✅ 柔軟な課金ポリシー設定
### 🔐 認証とセキュリティ
- 🤖 LinuxDO認証ログイン- 📱 Telegram認証ログイン- 🔑 OIDC統一認証
### 🚀 高度な機能
**APIフォーマットサポート:**- ⚡ [OpenAI Responses](https://docs.newapi.pro/api/openai-responses)- ⚡ [OpenAI Realtime API](https://docs.newapi.pro/api/openai-realtime)(Azureを含む)- ⚡ [Claude Messages](https://docs.newapi.pro/api/anthropic-chat)- ⚡ [Google Gemini](https://docs.newapi.pro/api/google-gemini-chat/)- 🔄 [Rerankモデル](https://docs.newapi.pro/api/jinaai-rerank)- ⚡ [OpenAI Realtime API](https://docs.newapi.pro/api/openai-realtime)- ⚡ [Claude Messages](https://docs.newapi.pro/api/anthropic-chat)- ⚡ [Google Gemini](https://docs.newapi.pro/api/google-gemini-chat/)- 🔄 [Rerankモデル](https://docs.newapi.pro/api/jinaai-rerank)(Cohere、Jina)
**インテリジェントルーティング:**- ⚖️ チャネル重み付けランダム- 🔄 失敗自動リトライ- 🚦 ユーザーレベルモデルレート制限
**フォーマット変換:**- 🔄 OpenAI ⇄ Claude Messages- 🔄 OpenAI ⇄ Gemini Chat- 🔄 思考からコンテンツへの機能
**Reasoning Effort サポート:**
<details><summary>詳細設定を表示</summary>
**OpenAIシリーズモデル:**- `o3-mini-high` - 高思考努力- `o3-mini-medium` - 中思考努力- `o3-mini-low` - 低思考努力- `gpt-5-high` - 高思考努力- `gpt-5-medium` - 中思考努力- `gpt-5-low` - 低思考努力
**Claude思考モデル:**- `claude-3-7-sonnet-20250219-thinking` - 思考モードを有効にする
**Google Geminiシリーズモデル:**- `gemini-2.5-flash-thinking` - 思考モードを有効にする- `gemini-2.5-flash-nothinking` - 思考モードを無効にする- `gemini-2.5-pro-thinking` - 思考モードを有効にする- `gemini-2.5-pro-thinking-128` - 思考モードを有効にし、思考予算を128トークンに設定する
</details>
---
## 🤖 モデルサポート
> 詳細については[APIドキュメント - 中継インターフェース](https://docs.newapi.pro/api)
| モデルタイプ | 説明 | ドキュメント ||---------|------|------|| 🤖 OpenAI GPTs | gpt-4-gizmo-* シリーズ | - || 🎨 Midjourney-Proxy | [Midjourney-Proxy(Plus)](https://github.com/novicezk/midjourney-proxy) | [ドキュメント](https://docs.newapi.pro/api/midjourney-proxy-image) || 🎵 Suno-API | [Suno API](https://github.com/Suno-API/Suno-API) | [ドキュメント](https://docs.newapi.pro/api/suno-music) || 🔄 Rerank | Cohere、Jina | [ドキュメント](https://docs.newapi.pro/api/jinaai-rerank) || 💬 Claude | Messagesフォーマット | [ドキュメント](https://docs.newapi.pro/api/suno-music) || 🌐 Gemini | Google Geminiフォーマット | [ドキュメント](https://docs.newapi.pro/api/google-gemini-chat/) || 🔧 Dify | ChatFlowモード | - || 🎯 カスタム | 完全な呼び出しアドレスの入力をサポート | - |
### 📡 サポートされているインターフェース
<details><summary>完全なインターフェースリストを表示</summary>
- [チャットインターフェース (Chat Completions)](https://docs.newapi.pro/api/openai-chat)- [レスポンスインターフェース (Responses)](https://docs.newapi.pro/api/openai-responses)- [イメージインターフェース (Image)](https://docs.newapi.pro/api/openai-image)- [オーディオインターフェース (Audio)](https://docs.newapi.pro/api/openai-audio)- [ビデオインターフェース (Video)](https://docs.newapi.pro/api/openai-video)- [エンベッドインターフェース (Embeddings)](https://docs.newapi.pro/api/openai-embeddings)- [再ランク付けインターフェース (Rerank)](https://docs.newapi.pro/api/jinaai-rerank)- [リアルタイム対話インターフェース (Realtime)](https://docs.newapi.pro/api/openai-realtime)- [Claudeチャット](https://docs.newapi.pro/api/anthropic-chat)- [Google Geminiチャット](https://docs.newapi.pro/api/google-gemini-chat/)
</details>
---
## 🚢 デプロイ
> [!TIP]> **最新のDockerイメージ:** `calciumion/new-api:latest`
### 📋 デプロイ要件
| コンポーネント | 要件 ||------|------|| **ローカルデータベース** | SQLite(Dockerは `/data` ディレクトリをマウントする必要があります)|| **リモートデータベース** | MySQL ≥ 5.7.8 または PostgreSQL ≥ 9.6 || **コンテナエンジン** | Docker / Docker Compose |
### ⚙️ 環境変数設定
<details><summary>一般的な環境変数設定</summary>
| 変数名 | 説明 | デフォルト値 ||--------|------|--------|| `SESSION_SECRET` | セッションシークレット(マルチマシンデプロイに必須) | - || `CRYPTO_SECRET` | 暗号化シークレット(Redisに必須) | - || `SQL_DSN** | データベース接続文字列 | - || `REDIS_CONN_STRING` | Redis接続文字列 | - || `STREAMING_TIMEOUT` | ストリーミング応答のタイムアウト時間(秒) | `300` || `AZURE_DEFAULT_API_VERSION` | Azure APIバージョン | `2025-04-01-preview` || `ERROR_LOG_ENABLED` | エラーログスイッチ | `false` |
📖 **完全な設定:** [環境変数ドキュメント](https://docs.newapi.pro/installation/environment-variables)
</details>
### 🔧 デプロイ方法
<details><summary><strong>方法 1: Docker Compose(推奨)</strong></summary>
```bash# プロジェクトをクローンgit clone https://github.com/QuantumNous/new-api.gitcd new-api
# 設定を編集nano docker-compose.yml
# サービスを起動docker-compose up -d```
</details>
<details><summary><strong>方法 2: Dockerコマンド</strong></summary>
**SQLiteを使用:**```bashdocker run --name new-api -d --restart always \ -p 3000:3000 \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
**MySQLを使用:**```bashdocker run --name new-api -d --restart always \ -p 3000:3000 \ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
> **💡 パス説明:** > - `./data:/data` - 相対パス、データは現在のディレクトリのdataフォルダに保存されます> - 絶対パスを使用することもできます:`/your/custom/path:/data`
</details>
<details><summary><strong>方法 3: 宝塔パネル</strong></summary>
1. 宝塔パネル(**9.2.0バージョン**以上)をインストールし、アプリケーションストアで**New-API**を検索してインストールします。
📖 [画像付きチュートリアル](./docs/BT.md)
</details>
### ⚠️ マルチマシンデプロイの注意事項
> [!WARNING]> - **必ず設定する必要があります** `SESSION_SECRET` - そうしないとマルチマシンデプロイ時にログイン状態が不一致になります> - **共有Redisは必ず設定する必要があります** `CRYPTO_SECRET` - そうしないとデータを復号化できません
### 🔄 チャネルリトライとキャッシュ
**リトライ設定:** `設定 → 運営設定 → 一般設定 → 失敗リトライ回数`
**キャッシュ設定:**- `REDIS_CONN_STRING`:Redisキャッシュ(推奨)- `MEMORY_CACHE_ENABLED`:メモリキャッシュ
---
## 🔗 関連プロジェクト
### 上流プロジェクト
| プロジェクト | 説明 ||------|------|| [One API](https://github.com/songquanpeng/one-api) | オリジナルプロジェクトベース || [Midjourney-Proxy](https://github.com/novicezk/midjourney-proxy) | Midjourneyインターフェースサポート |
### 補助ツール
| プロジェクト | 説明 ||------|------|| [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool) | キー使用量クォータ照会ツール || [new-api-horizon](https://github.com/Calcium-Ion/new-api-horizon) | New API高性能最適化版 |
---
## 💬 ヘルプサポート
### 📖 ドキュメントリソース
| リソース | リンク ||------|------|| 📘 よくある質問 | [FAQ](https://docs.newapi.pro/support/faq) || 💬 コミュニティ交流 | [交流チャネル](https://docs.newapi.pro/support/community-interaction) || 🐛 問題のフィードバック | [問題フィードバック](https://docs.newapi.pro/support/feedback-issues) || 📚 完全なドキュメント | [公式ドキュメント](https://docs.newapi.pro/support) |
### 🤝 貢献ガイド
あらゆる形の貢献を歓迎します!
- 🐛 バグを報告する- 💡 新しい機能を提案する- 📝 ドキュメントを改善する- 🔧 コードを提出する
---
## 🌟 スター履歴
<div align="center">
[](https://star-history.com/#Calcium-Ion/new-api&Date)
</div>
---
<div align="center">
### 💖 New APIをご利用いただきありがとうございます
このプロジェクトがあなたのお役に立てたなら、ぜひ ⭐️ スターをください!
**[公式ドキュメント](https://docs.newapi.pro/)** • **[問題フィードバック](https://github.com/Calcium-Ion/new-api/issues)** • **[最新リリース](https://github.com/Calcium-Ion/new-api/releases)**
<sub>❤️ で構築された QuantumNous</sub>
</div>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459---title: New APIemoji: 🚀colorFrom: bluecolorTo: purplesdk: dockerapp_port: 7860pinned: falselicense: mit---
<div align="center">

# New API
🍥 **新一代大模型网关与AI资产管理系统**
<p align="center"> <strong>中文</strong> | <a href="./README.en.md">English</a> | <a href="./README.fr.md">Français</a> | <a href="./README.ja.md">日本語</a></p>
<p align="center"> <a href="https://raw.githubusercontent.com/Calcium-Ion/new-api/main/LICENSE"> <img src="https://img.shields.io/github/license/Calcium-Ion/new-api?color=brightgreen" alt="license"> </a> <a href="https://github.com/Calcium-Ion/new-api/releases/latest"> <img src="https://img.shields.io/github/v/release/Calcium-Ion/new-api?color=brightgreen&include_prereleases" alt="release"> </a> <a href="https://github.com/users/Calcium-Ion/packages/container/package/new-api"> <img src="https://img.shields.io/badge/docker-ghcr.io-blue" alt="docker"> </a> <a href="https://hub.docker.com/r/CalciumIon/new-api"> <img src="https://img.shields.io/badge/docker-dockerHub-blue" alt="docker"> </a> <a href="https://goreportcard.com/report/github.com/Calcium-Ion/new-api"> <img src="https://goreportcard.com/badge/github.com/Calcium-Ion/new-api" alt="GoReportCard"> </a></p>
<p align="center"> <a href="https://trendshift.io/repositories/8227" target="_blank"> <img src="https://trendshift.io/api/badge/repositories/8227" alt="Calcium-Ion%2Fnew-api | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/> </a></p>
<p align="center"> <a href="#-快速开始">快速开始</a> • <a href="#-主要特性">主要特性</a> • <a href="#-部署">部署</a> • <a href="#-文档">文档</a> • <a href="#-帮助支持">帮助</a></p>
</div>
## 📝 项目说明
> [!NOTE] > 本项目为开源项目,在 [One API](https://github.com/songquanpeng/one-api) 的基础上进行二次开发
> [!IMPORTANT] > - 本项目仅供个人学习使用,不保证稳定性,且不提供任何技术支持> - 使用者必须在遵循 OpenAI 的 [使用条款](https://openai.com/policies/terms-of-use) 以及**法律法规**的情况下使用,不得用于非法用途> - 根据 [《生成式人工智能服务管理暂行办法》](http://www.cac.gov.cn/2023-07/13/c_1690898327029107.htm) 的要求,请勿对中国地区公众提供一切未经备案的生成式人工智能服务
---
## 🤝 我们信任的合作伙伴
<p align="center"> <em>排名不分先后</em></p>
<p align="center"> <a href="https://www.cherry-ai.com/" target="_blank"> <img src="./docs/images/cherry-studio.png" alt="Cherry Studio" height="80" /> </a> <a href="https://bda.pku.edu.cn/" target="_blank"> <img src="./docs/images/pku.png" alt="北京大学" height="80" /> </a> <a href="https://www.compshare.cn/?ytag=GPU_yy_gh_newapi" target="_blank"> <img src="./docs/images/ucloud.png" alt="UCloud 优刻得" height="80" /> </a> <a href="https://www.aliyun.com/" target="_blank"> <img src="./docs/images/aliyun.png" alt="阿里云" height="80" /> </a> <a href="https://io.net/" target="_blank"> <img src="./docs/images/io-net.png" alt="IO.NET" height="80" /> </a></p>
---
## 🙏 特别鸣谢
<p align="center"> <a href="https://www.jetbrains.com/?from=new-api" target="_blank"> <img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="JetBrains Logo" width="120" /> </a></p>
<p align="center"> <strong>感谢 <a href="https://www.jetbrains.com/?from=new-api">JetBrains</a> 为本项目提供免费的开源开发许可证</strong></p>
---
## 🚀 快速开始
### 使用 Docker Compose(推荐)
```bash# 克隆项目git clone https://github.com/QuantumNous/new-api.gitcd new-api
# 编辑 docker-compose.yml 配置nano docker-compose.yml
# 启动服务docker-compose up -d```
<details><summary><strong>使用 Docker 命令</strong></summary>
```bash# 拉取最新镜像docker pull calciumion/new-api:latest
# 使用 SQLite(默认)docker run --name new-api -d --restart always \ -p 3000:3000 \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest
# 使用 MySQLdocker run --name new-api -d --restart always \ -p 3000:3000 \ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
> **💡 提示:** `-v ./data:/data` 会将数据保存在当前目录的 `data` 文件夹中,你也可以改为绝对路径如 `-v /your/custom/path:/data`
</details>
---
🎉 部署完成后,访问 `http://localhost:3000` 即可使用!
📖 更多部署方式请参考 [部署指南](https://docs.newapi.pro/installation)
---
## 📚 文档
<div align="center">
### 📖 [官方文档](https://docs.newapi.pro/) | [](https://deepwiki.com/QuantumNous/new-api)
</div>
**快速导航:**
| 分类 | 链接 ||------|------|| 🚀 部署指南 | [安装文档](https://docs.newapi.pro/installation) || ⚙️ 环境配置 | [环境变量](https://docs.newapi.pro/installation/environment-variables) || 📡 接口文档 | [API 文档](https://docs.newapi.pro/api) || ❓ 常见问题 | [FAQ](https://docs.newapi.pro/support/faq) || 💬 社区交流 | [交流渠道](https://docs.newapi.pro/support/community-interaction) |
---
## ✨ 主要特性
> 详细特性请参考 [特性说明](https://docs.newapi.pro/wiki/features-introduction)
### 🎨 核心功能
| 特性 | 说明 ||------|------|| 🎨 全新 UI | 现代化的用户界面设计 || 🌍 多语言 | 支持中文、英文、法语、日语 || 🔄 数据兼容 | 完全兼容原版 One API 数据库 || 📈 数据看板 | 可视化控制台与统计分析 || 🔒 权限管理 | 令牌分组、模型限制、用户管理 |
### 💰 支付与计费
- ✅ 在线充值(易支付、Stripe)- ✅ 模型按次数收费- ✅ 缓存计费支持(OpenAI、Azure、DeepSeek、Claude、Qwen等所有支持的模型)- ✅ 灵活的计费策略配置
### 🔐 授权与安全
- 😈 Discord 授权登录- 🤖 LinuxDO 授权登录- 📱 Telegram 授权登录- 🔑 OIDC 统一认证- 🔍 Key 查询使用额度(配合 [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool))
### 🚀 高级功能
**API 格式支持:**- ⚡ [OpenAI Responses](https://docs.newapi.pro/api/openai-responses)- ⚡ [OpenAI Realtime API](https://docs.newapi.pro/api/openai-realtime)(含 Azure)- ⚡ [Claude Messages](https://docs.newapi.pro/api/anthropic-chat)- ⚡ [Google Gemini](https://docs.newapi.pro/api/google-gemini-chat/)- 🔄 [Rerank 模型](https://docs.newapi.pro/api/jinaai-rerank)(Cohere、Jina)
**智能路由:**- ⚖️ 渠道加权随机- 🔄 失败自动重试- 🚦 用户级别模型限流
**格式转换:**- 🔄 OpenAI ⇄ Claude Messages- 🔄 OpenAI ⇄ Gemini Chat- 🔄 思考转内容功能
**Reasoning Effort 支持:**
<details><summary>查看详细配置</summary>
**OpenAI 系列模型:**- `o3-mini-high` - High reasoning effort- `o3-mini-medium` - Medium reasoning effort- `o3-mini-low` - Low reasoning effort- `gpt-5-high` - High reasoning effort- `gpt-5-medium` - Medium reasoning effort- `gpt-5-low` - Low reasoning effort
**Claude 思考模型:**- `claude-3-7-sonnet-20250219-thinking` - 启用思考模式
**Google Gemini 系列模型:**- `gemini-2.5-flash-thinking` - 启用思考模式- `gemini-2.5-flash-nothinking` - 禁用思考模式- `gemini-2.5-pro-thinking` - 启用思考模式- `gemini-2.5-pro-thinking-128` - 启用思考模式,并设置思考预算为128tokens
</details>
---
## 🤖 模型支持
> 详情请参考 [接口文档 - 中继接口](https://docs.newapi.pro/api)
| 模型类型 | 说明 | 文档 ||---------|------|------|| 🤖 OpenAI GPTs | gpt-4-gizmo-* 系列 | - || 🎨 Midjourney-Proxy | [Midjourney-Proxy(Plus)](https://github.com/novicezk/midjourney-proxy) | [文档](https://docs.newapi.pro/api/midjourney-proxy-image) || 🎵 Suno-API | [Suno API](https://github.com/Suno-API/Suno-API) | [文档](https://docs.newapi.pro/api/suno-music) || 🔄 Rerank | Cohere、Jina | [文档](https://docs.newapi.pro/api/jinaai-rerank) || 💬 Claude | Messages 格式 | [文档](https://docs.newapi.pro/api/anthropic-chat) || 🌐 Gemini | Google Gemini 格式 | [文档](https://docs.newapi.pro/api/google-gemini-chat/) || 🔧 Dify | ChatFlow 模式 | - || 🎯 自定义 | 支持完整调用地址 | - |
### 📡 支持的接口
<details><summary>查看完整接口列表</summary>
- [聊天接口 (Chat Completions)](https://docs.newapi.pro/api/openai-chat)- [响应接口 (Responses)](https://docs.newapi.pro/api/openai-responses)- [图像接口 (Image)](https://docs.newapi.pro/api/openai-image)- [音频接口 (Audio)](https://docs.newapi.pro/api/openai-audio)- [视频接口 (Video)](https://docs.newapi.pro/api/openai-video)- [嵌入接口 (Embeddings)](https://docs.newapi.pro/api/openai-embeddings)- [重排序接口 (Rerank)](https://docs.newapi.pro/api/jinaai-rerank)- [实时对话 (Realtime)](https://docs.newapi.pro/api/openai-realtime)- [Claude 聊天](https://docs.newapi.pro/api/anthropic-chat)- [Google Gemini 聊天](https://docs.newapi.pro/api/google-gemini-chat)
</details>
---
## 🚢 部署
> [!TIP]> **最新版 Docker 镜像:** `calciumion/new-api:latest`
### 📋 部署要求
| 组件 | 要求 ||------|------|| **本地数据库** | SQLite(Docker 需挂载 `/data` 目录)|| **远程数据库** | MySQL ≥ 5.7.8 或 PostgreSQL ≥ 9.6 || **容器引擎** | Docker / Docker Compose |
### ⚙️ 环境变量配置
<details><summary>常用环境变量配置</summary>
| 变量名 | 说明 | 默认值 ||--------|------|--------|| `SESSION_SECRET` | 会话密钥(多机部署必须) | - || `CRYPTO_SECRET` | 加密密钥(Redis 必须) | - || `SQL_DSN` | 数据库连接字符串 | - || `REDIS_CONN_STRING` | Redis 连接字符串 | - || `STREAMING_TIMEOUT` | 流式超时时间(秒) | `300` || `AZURE_DEFAULT_API_VERSION` | Azure API 版本 | `2025-04-01-preview` || `ERROR_LOG_ENABLED` | 错误日志开关 | `false` |
📖 **完整配置:** [环境变量文档](https://docs.newapi.pro/installation/environment-variables)
</details>
### 🔧 部署方式
<details><summary><strong>方式 1:Docker Compose(推荐)</strong></summary>
```bash# 克隆项目git clone https://github.com/QuantumNous/new-api.gitcd new-api
# 编辑配置nano docker-compose.yml
# 启动服务docker-compose up -d```
</details>
<details><summary><strong>方式 2:Docker 命令</strong></summary>
**使用 SQLite:**```bashdocker run --name new-api -d --restart always \ -p 3000:3000 \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
**使用 MySQL:**```bashdocker run --name new-api -d --restart always \ -p 3000:3000 \ -e SQL_DSN="root:123456@tcp(localhost:3306)/oneapi" \ -e TZ=Asia/Shanghai \ -v ./data:/data \ calciumion/new-api:latest```
> **💡 路径说明:** > - `./data:/data` - 相对路径,数据保存在当前目录的 data 文件夹> - 也可使用绝对路径,如:`/your/custom/path:/data`
</details>
<details><summary><strong>方式 3:宝塔面板</strong></summary>
1. 安装宝塔面板(≥ 9.2.0 版本)2. 在应用商店搜索 **New-API**3. 一键安装
📖 [图文教程](./docs/BT.md)
</details>
### ⚠️ 多机部署注意事项
> [!WARNING]> - **必须设置** `SESSION_SECRET` - 否则登录状态不一致> - **公用 Redis 必须设置** `CRYPTO_SECRET` - 否则数据无法解密
### 🔄 渠道重试与缓存
**重试配置:** `设置 → 运营设置 → 通用设置 → 失败重试次数`
**缓存配置:**- `REDIS_CONN_STRING`:Redis 缓存(推荐)- `MEMORY_CACHE_ENABLED`:内存缓存
---
## 🔗 相关项目
### 上游项目
| 项目 | 说明 ||------|------|| [One API](https://github.com/songquanpeng/one-api) | 原版项目基础 || [Midjourney-Proxy](https://github.com/novicezk/midjourney-proxy) | Midjourney 接口支持 |
### 配套工具
| 项目 | 说明 ||------|------|| [neko-api-key-tool](https://github.com/Calcium-Ion/neko-api-key-tool) | Key 额度查询工具 || [new-api-horizon](https://github.com/Calcium-Ion/new-api-horizon) | New API 高性能优化版 |
---
## 💬 帮助支持
### 📖 文档资源
| 资源 | 链接 ||------|------|| 📘 常见问题 | [FAQ](https://docs.newapi.pro/support/faq) || 💬 社区交流 | [交流渠道](https://docs.newapi.pro/support/community-interaction) || 🐛 反馈问题 | [问题反馈](https://docs.newapi.pro/support/feedback-issues) || 📚 完整文档 | [官方文档](https://docs.newapi.pro/support) |
### 🤝 贡献指南
欢迎各种形式的贡献!
- 🐛 报告 Bug- 💡 提出新功能- 📝 改进文档- 🔧 提交代码
---
## 🌟 Star History
<div align="center">
[](https://star-history.com/#Calcium-Ion/new-api&Date)
</div>
---
<div align="center">
### 💖 感谢使用 New API
如果这个项目对你有帮助,欢迎给我们一个 ⭐️ Star!
**[官方文档](https://docs.newapi.pro/)** • **[问题反馈](https://github.com/Calcium-Ion/new-api/issues)** • **[最新发布](https://github.com/Calcium-Ion/new-api/releases)**
<sub>Built with ❤️ by QuantumNous</sub>
</div>123456UPDATE usersSET quota = quota + ( SELECT SUM(remain_quota) FROM tokens WHERE tokens.user_id = users.id)1234567891011121314151617INSERT INTO abilities (`group`, model, channel_id, enabled)SELECT c.`group`, m.model, c.id, 1FROM channels cCROSS JOIN ( SELECT 'gpt-3.5-turbo' AS model UNION ALL SELECT 'gpt-3.5-turbo-0301' AS model UNION ALL SELECT 'gpt-4' AS model UNION ALL SELECT 'gpt-4-0314' AS model) AS mWHERE c.status = 1 AND NOT EXISTS ( SELECT 1 FROM abilities a WHERE a.`group` = c.`group` AND a.model = m.model AND a.channel_id = c.id);12345678910111213141516171819202122232425262728293031323334353637383940#!/bin/bash
if [ $# -lt 3 ]; then echo "Usage: time_test.sh <domain> <key> <count> [<model>]" exit 1fi
domain=$1key=$2count=$3model=${4:-"gpt-3.5-turbo"} # 设置默认模型为 gpt-3.5-turbo
total_time=0times=()
for ((i=1; i<=count; i++)); do result=$(curl -o /dev/null -s -w "%{http_code} %{time_total}\\n" \ https://"$domain"/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $key" \ -d '{"messages": [{"content": "echo hi", "role": "user"}], "model": "'"$model"'", "stream": false, "max_tokens": 1}') http_code=$(echo "$result" | awk '{print $1}') time=$(echo "$result" | awk '{print $2}') echo "HTTP status code: $http_code, Time taken: $time" total_time=$(bc <<< "$total_time + $time") times+=("$time")done
average_time=$(echo "scale=4; $total_time / $count" | bc)
sum_of_squares=0for time in "${times[@]}"; do difference=$(echo "scale=4; $time - $average_time" | bc) square=$(echo "scale=4; $difference * $difference" | bc) sum_of_squares=$(echo "scale=4; $sum_of_squares + $square" | bc)done
standard_deviation=$(echo "scale=4; sqrt($sum_of_squares / $count)" | bc)
echo "Average time: $average_time±$standard_deviation"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081package common
import "github.com/QuantumNous/new-api/constant"
func ChannelType2APIType(channelType int) (int, bool) { apiType := -1 switch channelType { case constant.ChannelTypeOpenAI: apiType = constant.APITypeOpenAI case constant.ChannelTypeAnthropic: apiType = constant.APITypeAnthropic case constant.ChannelTypeBaidu: apiType = constant.APITypeBaidu case constant.ChannelTypePaLM: apiType = constant.APITypePaLM case constant.ChannelTypeZhipu: apiType = constant.APITypeZhipu case constant.ChannelTypeAli: apiType = constant.APITypeAli case constant.ChannelTypeXunfei: apiType = constant.APITypeXunfei case constant.ChannelTypeAIProxyLibrary: apiType = constant.APITypeAIProxyLibrary case constant.ChannelTypeTencent: apiType = constant.APITypeTencent case constant.ChannelTypeGemini: apiType = constant.APITypeGemini case constant.ChannelTypeZhipu_v4: apiType = constant.APITypeZhipuV4 case constant.ChannelTypeOllama: apiType = constant.APITypeOllama case constant.ChannelTypePerplexity: apiType = constant.APITypePerplexity case constant.ChannelTypeAws: apiType = constant.APITypeAws case constant.ChannelTypeCohere: apiType = constant.APITypeCohere case constant.ChannelTypeDify: apiType = constant.APITypeDify case constant.ChannelTypeJina: apiType = constant.APITypeJina case constant.ChannelCloudflare: apiType = constant.APITypeCloudflare case constant.ChannelTypeSiliconFlow: apiType = constant.APITypeSiliconFlow case constant.ChannelTypeVertexAi: apiType = constant.APITypeVertexAi case constant.ChannelTypeMistral: apiType = constant.APITypeMistral case constant.ChannelTypeDeepSeek: apiType = constant.APITypeDeepSeek case constant.ChannelTypeMokaAI: apiType = constant.APITypeMokaAI case constant.ChannelTypeVolcEngine: apiType = constant.APITypeVolcEngine case constant.ChannelTypeBaiduV2: apiType = constant.APITypeBaiduV2 case constant.ChannelTypeOpenRouter: apiType = constant.APITypeOpenRouter case constant.ChannelTypeXinference: apiType = constant.APITypeXinference case constant.ChannelTypeXai: apiType = constant.APITypeXai case constant.ChannelTypeCoze: apiType = constant.APITypeCoze case constant.ChannelTypeJimeng: apiType = constant.APITypeJimeng case constant.ChannelTypeMoonshot: apiType = constant.APITypeMoonshot case constant.ChannelTypeSubmodel: apiType = constant.APITypeSubmodel case constant.ChannelTypeMiniMax: apiType = constant.APITypeMiniMax case constant.ChannelTypeReplicate: apiType = constant.APITypeReplicate } if apiType == -1 { return constant.APITypeOpenAI, false } return apiType, true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296package common
import ( "context" "encoding/binary" "fmt" "io"
"github.com/abema/go-mp4" "github.com/go-audio/aiff" "github.com/go-audio/wav" "github.com/jfreymuth/oggvorbis" "github.com/mewkiz/flac" "github.com/pkg/errors" "github.com/tcolgate/mp3" "github.com/yapingcat/gomedia/go-codec")
// GetAudioDuration 使用纯 Go 库获取音频文件的时长(秒)。// 它不再依赖外部的 ffmpeg 或 ffprobe 程序。func GetAudioDuration(ctx context.Context, f io.ReadSeeker, ext string) (duration float64, err error) { SysLog(fmt.Sprintf("GetAudioDuration: ext=%s", ext)) // 根据文件扩展名选择解析器 switch ext { case ".mp3": duration, err = getMP3Duration(f) case ".wav": duration, err = getWAVDuration(f) case ".flac": duration, err = getFLACDuration(f) case ".m4a", ".mp4": duration, err = getM4ADuration(f) case ".ogg", ".oga", ".opus": duration, err = getOGGDuration(f) if err != nil { duration, err = getOpusDuration(f) } case ".aiff", ".aif", ".aifc": duration, err = getAIFFDuration(f) case ".webm": duration, err = getWebMDuration(f) case ".aac": duration, err = getAACDuration(f) default: return 0, fmt.Errorf("unsupported audio format: %s", ext) } SysLog(fmt.Sprintf("GetAudioDuration: duration=%f", duration)) return duration, err}
// getMP3Duration 解析 MP3 文件以获取时长。// 注意:对于 VBR (Variable Bitrate) MP3,这个估算可能不完全精确,但通常足够好。// FFmpeg 在这种情况下会扫描整个文件来获得精确值,但这里的库提供了快速估算。func getMP3Duration(r io.Reader) (float64, error) { d := mp3.NewDecoder(r) var f mp3.Frame skipped := 0 duration := 0.0
for { if err := d.Decode(&f, &skipped); err != nil { if err == io.EOF { break } return 0, errors.Wrap(err, "failed to decode mp3 frame") } duration += f.Duration().Seconds() } return duration, nil}
// getWAVDuration 解析 WAV 文件头以获取时长。func getWAVDuration(r io.ReadSeeker) (float64, error) { dec := wav.NewDecoder(r) if !dec.IsValidFile() { return 0, errors.New("invalid wav file") } d, err := dec.Duration() if err != nil { return 0, errors.Wrap(err, "failed to get wav duration") } return d.Seconds(), nil}
// getFLACDuration 解析 FLAC 文件的 STREAMINFO 块。func getFLACDuration(r io.Reader) (float64, error) { stream, err := flac.Parse(r) if err != nil { return 0, errors.Wrap(err, "failed to parse flac stream") } defer stream.Close()
// 时长 = 总采样数 / 采样率 duration := float64(stream.Info.NSamples) / float64(stream.Info.SampleRate) return duration, nil}
// getM4ADuration 解析 M4A/MP4 文件的 'mvhd' box。func getM4ADuration(r io.ReadSeeker) (float64, error) { // go-mp4 库需要 ReadSeeker 接口 info, err := mp4.Probe(r) if err != nil { return 0, errors.Wrap(err, "failed to probe m4a/mp4 file") } // 时长 = Duration / Timescale return float64(info.Duration) / float64(info.Timescale), nil}
// getOGGDuration 解析 OGG/Vorbis 文件以获取时长。func getOGGDuration(r io.ReadSeeker) (float64, error) { // 重置 reader 到开头 if _, err := r.Seek(0, io.SeekStart); err != nil { return 0, errors.Wrap(err, "failed to seek ogg file") }
reader, err := oggvorbis.NewReader(r) if err != nil { return 0, errors.Wrap(err, "failed to create ogg vorbis reader") }
// 计算时长 = 总采样数 / 采样率 // 需要读取整个文件来获取总采样数 channels := reader.Channels() sampleRate := reader.SampleRate()
// 估算方法:读取到文件结尾 var totalSamples int64 buf := make([]float32, 4096*channels) for { n, err := reader.Read(buf) if err == io.EOF { break } if err != nil { return 0, errors.Wrap(err, "failed to read ogg samples") } totalSamples += int64(n / channels) }
duration := float64(totalSamples) / float64(sampleRate) return duration, nil}
// getOpusDuration 解析 Opus 文件(在 OGG 容器中)以获取时长。func getOpusDuration(r io.ReadSeeker) (float64, error) { // Opus 通常封装在 OGG 容器中 // 我们需要解析 OGG 页面来获取时长信息 if _, err := r.Seek(0, io.SeekStart); err != nil { return 0, errors.Wrap(err, "failed to seek opus file") }
// 读取 OGG 页面头部 var totalGranulePos int64 buf := make([]byte, 27) // OGG 页面头部最小大小
for { n, err := r.Read(buf) if err == io.EOF { break } if err != nil { return 0, errors.Wrap(err, "failed to read opus/ogg page") } if n < 27 { break }
// 检查 OGG 页面标识 "OggS" if string(buf[0:4]) != "OggS" { // 跳过一些字节继续寻找 if _, err := r.Seek(-26, io.SeekCurrent); err != nil { break } continue }
// 读取 granule position (字节 6-13, 小端序) granulePos := int64(binary.LittleEndian.Uint64(buf[6:14])) if granulePos > totalGranulePos { totalGranulePos = granulePos }
// 读取段表大小 numSegments := int(buf[26]) segmentTable := make([]byte, numSegments) if _, err := io.ReadFull(r, segmentTable); err != nil { break }
// 计算页面数据大小并跳过 var pageSize int for _, segSize := range segmentTable { pageSize += int(segSize) } if _, err := r.Seek(int64(pageSize), io.SeekCurrent); err != nil { break } }
// Opus 的采样率固定为 48000 Hz duration := float64(totalGranulePos) / 48000.0 return duration, nil}
// getAIFFDuration 解析 AIFF 文件头以获取时长。func getAIFFDuration(r io.ReadSeeker) (float64, error) { if _, err := r.Seek(0, io.SeekStart); err != nil { return 0, errors.Wrap(err, "failed to seek aiff file") }
dec := aiff.NewDecoder(r) if !dec.IsValidFile() { return 0, errors.New("invalid aiff file") }
d, err := dec.Duration() if err != nil { return 0, errors.Wrap(err, "failed to get aiff duration") }
return d.Seconds(), nil}
// getWebMDuration 解析 WebM 文件以获取时长。// WebM 使用 Matroska 容器格式func getWebMDuration(r io.ReadSeeker) (float64, error) { if _, err := r.Seek(0, io.SeekStart); err != nil { return 0, errors.Wrap(err, "failed to seek webm file") }
// WebM/Matroska 文件的解析比较复杂 // 这里提供一个简化的实现,读取 EBML 头部 // 对于完整的 WebM 解析,可能需要使用专门的库
// 简单实现:查找 Duration 元素 // WebM Duration 的 Element ID 是 0x4489 // 这是一个简化版本,可能不适用于所有 WebM 文件 buf := make([]byte, 8192) n, err := r.Read(buf) if err != nil && err != io.EOF { return 0, errors.Wrap(err, "failed to read webm file") }
// 尝试查找 Duration 元素(这是一个简化的方法) // 实际的 WebM 解析需要完整的 EBML 解析器 // 这里返回错误,建议使用专门的库 if n > 0 { // 检查 EBML 标识 if len(buf) >= 4 && binary.BigEndian.Uint32(buf[0:4]) == 0x1A45DFA3 { // 这是一个有效的 EBML 文件 // 但完整解析需要更复杂的逻辑 return 0, errors.New("webm duration parsing requires full EBML parser (consider using ffprobe for webm files)") } }
return 0, errors.New("failed to parse webm file")}
// getAACDuration 解析 AAC (ADTS格式) 文件以获取时长。// 使用 gomedia 库来解析 AAC ADTS 帧func getAACDuration(r io.ReadSeeker) (float64, error) { if _, err := r.Seek(0, io.SeekStart); err != nil { return 0, errors.Wrap(err, "failed to seek aac file") }
// 读取整个文件内容 data, err := io.ReadAll(r) if err != nil { return 0, errors.Wrap(err, "failed to read aac file") }
var totalFrames int64 var sampleRate int
// 使用 gomedia 的 SplitAACFrame 函数来分割 AAC 帧 codec.SplitAACFrame(data, func(aac []byte) { // 解析 ADTS 头部以获取采样率信息 if len(aac) >= 7 { // 使用 ConvertADTSToASC 来获取音频配置信息 asc, err := codec.ConvertADTSToASC(aac) if err == nil && sampleRate == 0 { sampleRate = codec.AACSampleIdxToSample(int(asc.Sample_freq_index)) } totalFrames++ } })
if sampleRate == 0 || totalFrames == 0 { return 0, errors.New("no valid aac frames found") }
// 每个 AAC ADTS 帧包含 1024 个采样 totalSamples := totalFrames * 1024 duration := float64(totalSamples) / float64(sampleRate) return duration, nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204package common
import ( //"os" //"strconv" "sync" "time"
"github.com/google/uuid")
var StartTime = time.Now().Unix() // unit: secondvar Version = "v0.0.0" // this hard coding will be replaced automatically when building, no need to manually changevar SystemName = "New API"var Footer = ""var Logo = ""var TopUpLink = ""
// var ChatLink = ""// var ChatLink2 = ""var QuotaPerUnit = 500 * 1000.0 // $0.002 / 1K tokens// 保留旧变量以兼容历史逻辑,实际展示由 general_setting.quota_display_type 控制var DisplayInCurrencyEnabled = truevar DisplayTokenStatEnabled = truevar DrawingEnabled = truevar TaskEnabled = truevar DataExportEnabled = truevar DataExportInterval = 5 // unit: minutevar DataExportDefaultTime = "hour" // unit: minutevar DefaultCollapseSidebar = false // default value of collapse sidebar
// Any options with "Secret", "Token" in its key won't be return by GetOptions
var SessionSecret = uuid.New().String()var CryptoSecret = uuid.New().String()
var OptionMap map[string]stringvar OptionMapRWMutex sync.RWMutex
var ItemsPerPage = 10var MaxRecentItems = 100
var PasswordLoginEnabled = truevar PasswordRegisterEnabled = truevar EmailVerificationEnabled = falsevar GitHubOAuthEnabled = falsevar LinuxDOOAuthEnabled = falsevar WeChatAuthEnabled = falsevar TelegramOAuthEnabled = falsevar TurnstileCheckEnabled = falsevar RegisterEnabled = true
var EmailDomainRestrictionEnabled = false // 是否启用邮箱域名限制var EmailAliasRestrictionEnabled = false // 是否启用邮箱别名限制var EmailDomainWhitelist = []string{ "gmail.com", "163.com", "126.com", "qq.com", "outlook.com", "hotmail.com", "icloud.com", "yahoo.com", "foxmail.com",}var EmailLoginAuthServerList = []string{ "smtp.sendcloud.net", "smtp.azurecomm.net",}
var DebugEnabled boolvar MemoryCacheEnabled bool
var LogConsumeEnabled = true
var SMTPServer = ""var SMTPPort = 587var SMTPSSLEnabled = falsevar SMTPAccount = ""var SMTPFrom = ""var SMTPToken = ""
var GitHubClientId = ""var GitHubClientSecret = ""var LinuxDOClientId = ""var LinuxDOClientSecret = ""var LinuxDOMinimumTrustLevel = 0
var WeChatServerAddress = ""var WeChatServerToken = ""var WeChatAccountQRCodeImageURL = ""
var TurnstileSiteKey = ""var TurnstileSecretKey = ""
var TelegramBotToken = ""var TelegramBotName = ""
var QuotaForNewUser = 0var QuotaForInviter = 0var QuotaForInvitee = 0var ChannelDisableThreshold = 5.0var AutomaticDisableChannelEnabled = falsevar AutomaticEnableChannelEnabled = falsevar QuotaRemindThreshold = 1000var PreConsumedQuota = 500
var RetryTimes = 0
//var RootUserEmail = ""
var IsMasterNode bool
var requestInterval intvar RequestInterval time.Duration
var SyncFrequency int // unit is second
var BatchUpdateEnabled = falsevar BatchUpdateInterval int
var RelayTimeout int // unit is second
var GeminiSafetySetting string
// https://docs.cohere.com/docs/safety-modes Type; NONE/CONTEXTUAL/STRICTvar CohereSafetySetting string
const ( RequestIdKey = "X-Oneapi-Request-Id")
const ( RoleGuestUser = 0 RoleCommonUser = 1 RoleAdminUser = 10 RoleRootUser = 100)
func IsValidateRole(role int) bool { return role == RoleGuestUser || role == RoleCommonUser || role == RoleAdminUser || role == RoleRootUser}
var ( FileUploadPermission = RoleGuestUser FileDownloadPermission = RoleGuestUser ImageUploadPermission = RoleGuestUser ImageDownloadPermission = RoleGuestUser)
// All duration's unit is seconds// Shouldn't larger then RateLimitKeyExpirationDurationvar ( GlobalApiRateLimitEnable bool GlobalApiRateLimitNum int GlobalApiRateLimitDuration int64
GlobalWebRateLimitEnable bool GlobalWebRateLimitNum int GlobalWebRateLimitDuration int64
CriticalRateLimitEnable bool CriticalRateLimitNum = 20 CriticalRateLimitDuration int64 = 20 * 60
UploadRateLimitNum = 10 UploadRateLimitDuration int64 = 60
DownloadRateLimitNum = 10 DownloadRateLimitDuration int64 = 60)
var RateLimitKeyExpirationDuration = 20 * time.Minute
const ( UserStatusEnabled = 1 // don't use 0, 0 is the default value! UserStatusDisabled = 2 // also don't use 0)
const ( TokenStatusEnabled = 1 // don't use 0, 0 is the default value! TokenStatusDisabled = 2 // also don't use 0 TokenStatusExpired = 3 TokenStatusExhausted = 4)
const ( RedemptionCodeStatusEnabled = 1 // don't use 0, 0 is the default value! RedemptionCodeStatusDisabled = 2 // also don't use 0 RedemptionCodeStatusUsed = 3 // also don't use 0)
const ( ChannelStatusUnknown = 0 ChannelStatusEnabled = 1 // don't use 0, 0 is the default value! ChannelStatusManuallyDisabled = 2 // also don't use 0 ChannelStatusAutoDisabled = 3)
const ( TopUpStatusPending = "pending" TopUpStatusSuccess = "success" TopUpStatusExpired = "expired")12345678910111213141516171819package common
import ( "fmt"
"github.com/jinzhu/copier")
func DeepCopy[T any](src *T) (*T, error) { if src == nil { return nil, fmt.Errorf("copy source cannot be nil") } var dst T err := copier.CopyWithOption(&dst, src, copier.Option{DeepCopy: true, IgnoreEmpty: true}) if err != nil { return nil, err } return &dst, nil}1234567891011121314151617181920212223242526272829303132package common
import ( "crypto/hmac" "crypto/sha256" "encoding/hex"
"golang.org/x/crypto/bcrypt")
func GenerateHMACWithKey(key []byte, data string) string { h := hmac.New(sha256.New, key) h.Write([]byte(data)) return hex.EncodeToString(h.Sum(nil))}
func GenerateHMAC(data string) string { h := hmac.New(sha256.New, []byte(CryptoSecret)) h.Write([]byte(data)) return hex.EncodeToString(h.Sum(nil))}
func Password2Hash(password string) (string, error) { passwordBytes := []byte(password) hashedPassword, err := bcrypt.GenerateFromPassword(passwordBytes, bcrypt.DefaultCost) return string(hashedPassword), err}
func ValidatePasswordAndHash(password string, hash string) bool { err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) return err == nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687// Copyright 2014 Manu Martinez-Almeida. All rights reserved.// Use of this source code is governed by a MIT style// license that can be found in the LICENSE file.
package common
import ( "fmt" "io" "net/http" "strings" "sync")
type stringWriter interface { io.Writer writeString(string) (int, error)}
type stringWrapper struct { io.Writer}
func (w stringWrapper) writeString(str string) (int, error) { return w.Writer.Write([]byte(str))}
func checkWriter(writer io.Writer) stringWriter { if w, ok := writer.(stringWriter); ok { return w } else { return stringWrapper{writer} }}
// Server-Sent Events// W3C Working Draft 29 October 2009// http://www.w3.org/TR/2009/WD-eventsource-20091029/
var contentType = []string{"text/event-stream"}var noCache = []string{"no-cache"}
var fieldReplacer = strings.NewReplacer( "\n", "\\n", "\r", "\\r")
var dataReplacer = strings.NewReplacer( "\n", "\n", "\r", "\\r")
type CustomEvent struct { Event string Id string Retry uint Data interface{}
Mutex sync.Mutex}
func encode(writer io.Writer, event CustomEvent) error { w := checkWriter(writer) return writeData(w, event.Data)}
func writeData(w stringWriter, data interface{}) error { dataReplacer.WriteString(w, fmt.Sprint(data)) if strings.HasPrefix(data.(string), "data") { w.writeString("\n\n") } return nil}
func (r CustomEvent) Render(w http.ResponseWriter) error { r.WriteContentType(w) return encode(w, r)}
func (r CustomEvent) WriteContentType(w http.ResponseWriter) { r.Mutex.Lock() defer r.Mutex.Unlock() header := w.Header() header["Content-Type"] = contentType
if _, exist := header["Cache-Control"]; !exist { header["Cache-Control"] = noCache }}123456789101112131415package common
const ( DatabaseTypeMySQL = "mysql" DatabaseTypeSQLite = "sqlite" DatabaseTypePostgreSQL = "postgres")
var UsingSQLite = falsevar UsingPostgreSQL = falsevar LogSqlType = DatabaseTypeSQLite // Default to SQLite for logging SQL queriesvar UsingMySQL = falsevar UsingClickHouse = false
var SQLitePath = "one-api.db?_busy_timeout=30000"12345678910111213141516171819202122232425262728293031323334353637383940package common
import ( "errors" "net/smtp" "strings")
type outlookAuth struct { username, password string}
func LoginAuth(username, password string) smtp.Auth { return &outlookAuth{username, password}}
func (a *outlookAuth) Start(_ *smtp.ServerInfo) (string, []byte, error) { return "LOGIN", []byte{}, nil}
func (a *outlookAuth) Next(fromServer []byte, more bool) ([]byte, error) { if more { switch string(fromServer) { case "Username:": return []byte(a.username), nil case "Password:": return []byte(a.password), nil default: return nil, errors.New("unknown fromServer") } } return nil, nil}
func isOutlookServer(server string) bool { // 兼容多地区的outlook邮箱和ofb邮箱 // 其实应该加一个Option来区分是否用LOGIN的方式登录 // 先临时兼容一下 return strings.Contains(server, "outlook") || strings.Contains(server, "onmicrosoft")}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293package common
import ( "crypto/tls" "encoding/base64" "fmt" "net/smtp" "slices" "strings" "time")
func generateMessageID() (string, error) { split := strings.Split(SMTPFrom, "@") if len(split) < 2 { return "", fmt.Errorf("invalid SMTP account") } domain := strings.Split(SMTPFrom, "@")[1] return fmt.Sprintf("<%d.%s@%s>", time.Now().UnixNano(), GetRandomString(12), domain), nil}
func SendEmail(subject string, receiver string, content string) error { if SMTPFrom == "" { // for compatibility SMTPFrom = SMTPAccount } id, err2 := generateMessageID() if err2 != nil { return err2 } if SMTPServer == "" && SMTPAccount == "" { return fmt.Errorf("SMTP 服务器未配置") } encodedSubject := fmt.Sprintf("=?UTF-8?B?%s?=", base64.StdEncoding.EncodeToString([]byte(subject))) mail := []byte(fmt.Sprintf("To: %s\r\n"+ "From: %s<%s>\r\n"+ "Subject: %s\r\n"+ "Date: %s\r\n"+ "Message-ID: %s\r\n"+ // 添加 Message-ID 头 "Content-Type: text/html; charset=UTF-8\r\n\r\n%s\r\n", receiver, SystemName, SMTPFrom, encodedSubject, time.Now().Format(time.RFC1123Z), id, content)) auth := smtp.PlainAuth("", SMTPAccount, SMTPToken, SMTPServer) addr := fmt.Sprintf("%s:%d", SMTPServer, SMTPPort) to := strings.Split(receiver, ";") var err error if SMTPPort == 465 || SMTPSSLEnabled { tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: SMTPServer, } conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", SMTPServer, SMTPPort), tlsConfig) if err != nil { return err } client, err := smtp.NewClient(conn, SMTPServer) if err != nil { return err } defer client.Close() if err = client.Auth(auth); err != nil { return err } if err = client.Mail(SMTPFrom); err != nil { return err } receiverEmails := strings.Split(receiver, ";") for _, receiver := range receiverEmails { if err = client.Rcpt(receiver); err != nil { return err } } w, err := client.Data() if err != nil { return err } _, err = w.Write(mail) if err != nil { return err } err = w.Close() if err != nil { return err } } else if isOutlookServer(SMTPAccount) || slices.Contains(EmailLoginAuthServerList, SMTPServer) { auth = LoginAuth(SMTPAccount, SMTPToken) err = smtp.SendMail(addr, auth, SMTPFrom, to, mail) } else { err = smtp.SendMail(addr, auth, SMTPFrom, to, mail) } if err != nil { SysError(fmt.Sprintf("failed to send email to %s: %v", receiver, err)) } return err}12345678910111213141516171819202122232425262728293031323334353637383940414243package common
import ( "embed" "io/fs" "net/http" "os"
"github.com/gin-contrib/static")
// Credit: https://github.com/gin-contrib/static/issues/19
type embedFileSystem struct { http.FileSystem}
func (e *embedFileSystem) Exists(prefix string, path string) bool { _, err := e.Open(path) if err != nil { return false } return true}
func (e *embedFileSystem) Open(name string) (http.File, error) { if name == "/" { // This will make sure the index page goes to NoRouter handler, // which will use the replaced index bytes with analytic codes. return nil, os.ErrNotExist } return e.FileSystem.Open(name)}
func EmbedFolder(fsEmbed embed.FS, targetPath string) static.ServeFileSystem { efs, err := fs.Sub(fsEmbed, targetPath) if err != nil { panic(err) } return &embedFileSystem{ FileSystem: http.FS(efs), }}123456789101112131415161718192021222324252627282930313233package common
import "github.com/QuantumNous/new-api/constant"
// EndpointInfo 描述单个端点的默认请求信息// path: 上游路径// method: HTTP 请求方式,例如 POST/GET// 目前均为 POST,后续可扩展//// json 标签用于直接序列化到 API 输出// 例如:{"path":"/v1/chat/completions","method":"POST"}
type EndpointInfo struct { Path string `json:"path"` Method string `json:"method"`}
// defaultEndpointInfoMap 保存内置端点的默认 Path 与 Methodvar defaultEndpointInfoMap = map[constant.EndpointType]EndpointInfo{ constant.EndpointTypeOpenAI: {Path: "/v1/chat/completions", Method: "POST"}, constant.EndpointTypeOpenAIResponse: {Path: "/v1/responses", Method: "POST"}, constant.EndpointTypeAnthropic: {Path: "/v1/messages", Method: "POST"}, constant.EndpointTypeGemini: {Path: "/v1beta/models/{model}:generateContent", Method: "POST"}, constant.EndpointTypeJinaRerank: {Path: "/rerank", Method: "POST"}, constant.EndpointTypeImageGeneration: {Path: "/v1/images/generations", Method: "POST"}, constant.EndpointTypeEmbeddings: {Path: "/v1/embeddings", Method: "POST"},}
// GetDefaultEndpointInfo 返回指定端点类型的默认信息以及是否存在func GetDefaultEndpointInfo(et constant.EndpointType) (EndpointInfo, bool) { info, ok := defaultEndpointInfoMap[et] return info, ok}12345678910111213141516171819202122232425262728293031323334353637383940414243package common
import "github.com/QuantumNous/new-api/constant"
// GetEndpointTypesByChannelType 获取渠道最优先端点类型(所有的渠道都支持 OpenAI 端点)func GetEndpointTypesByChannelType(channelType int, modelName string) []constant.EndpointType { var endpointTypes []constant.EndpointType switch channelType { case constant.ChannelTypeJina: endpointTypes = []constant.EndpointType{constant.EndpointTypeJinaRerank} //case constant.ChannelTypeMidjourney, constant.ChannelTypeMidjourneyPlus: // endpointTypes = []constant.EndpointType{constant.EndpointTypeMidjourney} //case constant.ChannelTypeSunoAPI: // endpointTypes = []constant.EndpointType{constant.EndpointTypeSuno} //case constant.ChannelTypeKling: // endpointTypes = []constant.EndpointType{constant.EndpointTypeKling} //case constant.ChannelTypeJimeng: // endpointTypes = []constant.EndpointType{constant.EndpointTypeJimeng} case constant.ChannelTypeAws: fallthrough case constant.ChannelTypeAnthropic: endpointTypes = []constant.EndpointType{constant.EndpointTypeAnthropic, constant.EndpointTypeOpenAI} case constant.ChannelTypeVertexAi: fallthrough case constant.ChannelTypeGemini: endpointTypes = []constant.EndpointType{constant.EndpointTypeGemini, constant.EndpointTypeOpenAI} case constant.ChannelTypeOpenRouter: // OpenRouter 只支持 OpenAI 端点 endpointTypes = []constant.EndpointType{constant.EndpointTypeOpenAI} case constant.ChannelTypeSora: endpointTypes = []constant.EndpointType{constant.EndpointTypeOpenAIVideo} default: if IsOpenAIResponseOnlyModel(modelName) { endpointTypes = []constant.EndpointType{constant.EndpointTypeOpenAIResponse} } else { endpointTypes = []constant.EndpointType{constant.EndpointTypeOpenAI} } } if IsImageGenerationModel(modelName) { // add to first endpointTypes = append([]constant.EndpointType{constant.EndpointTypeImageGeneration}, endpointTypes...) } return endpointTypes}1234567891011121314151617181920212223242526272829303132333435363738package common
import ( "fmt" "os" "strconv")
func GetEnvOrDefault(env string, defaultValue int) int { if env == "" || os.Getenv(env) == "" { return defaultValue } num, err := strconv.Atoi(os.Getenv(env)) if err != nil { SysError(fmt.Sprintf("failed to parse %s: %s, using default value: %d", env, err.Error(), defaultValue)) return defaultValue } return num}
func GetEnvOrDefaultString(env string, defaultValue string) string { if env == "" || os.Getenv(env) == "" { return defaultValue } return os.Getenv(env)}
func GetEnvOrDefaultBool(env string, defaultValue bool) bool { if env == "" || os.Getenv(env) == "" { return defaultValue } b, err := strconv.ParseBool(os.Getenv(env)) if err != nil { SysError(fmt.Sprintf("failed to parse %s: %s, using default value: %t", env, err.Error(), defaultValue)) return defaultValue } return b}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234package common
import ( "bytes" "errors" "io" "mime" "mime/multipart" "net/http" "net/url" "strings" "time"
"github.com/QuantumNous/new-api/constant"
"github.com/gin-gonic/gin")
const KeyRequestBody = "key_request_body"
func GetRequestBody(c *gin.Context) ([]byte, error) { requestBody, _ := c.Get(KeyRequestBody) if requestBody != nil { return requestBody.([]byte), nil } requestBody, err := io.ReadAll(c.Request.Body) if err != nil { return nil, err } _ = c.Request.Body.Close() c.Set(KeyRequestBody, requestBody) return requestBody.([]byte), nil}
func UnmarshalBodyReusable(c *gin.Context, v any) error { requestBody, err := GetRequestBody(c) if err != nil { return err } //if DebugEnabled { // println("UnmarshalBodyReusable request body:", string(requestBody)) //} contentType := c.Request.Header.Get("Content-Type") if strings.HasPrefix(contentType, "application/json") { err = Unmarshal(requestBody, v) } else if strings.Contains(contentType, gin.MIMEPOSTForm) { err = parseFormData(requestBody, v) } else if strings.Contains(contentType, gin.MIMEMultipartPOSTForm) { err = parseMultipartFormData(c, requestBody, v) } else { // skip for now // TODO: someday non json request have variant model, we will need to implementation this } if err != nil { return err } // Reset request body c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody)) return nil}
func SetContextKey(c *gin.Context, key constant.ContextKey, value any) { c.Set(string(key), value)}
func GetContextKey(c *gin.Context, key constant.ContextKey) (any, bool) { return c.Get(string(key))}
func GetContextKeyString(c *gin.Context, key constant.ContextKey) string { return c.GetString(string(key))}
func GetContextKeyInt(c *gin.Context, key constant.ContextKey) int { return c.GetInt(string(key))}
func GetContextKeyBool(c *gin.Context, key constant.ContextKey) bool { return c.GetBool(string(key))}
func GetContextKeyStringSlice(c *gin.Context, key constant.ContextKey) []string { return c.GetStringSlice(string(key))}
func GetContextKeyStringMap(c *gin.Context, key constant.ContextKey) map[string]any { return c.GetStringMap(string(key))}
func GetContextKeyTime(c *gin.Context, key constant.ContextKey) time.Time { return c.GetTime(string(key))}
func GetContextKeyType[T any](c *gin.Context, key constant.ContextKey) (T, bool) { if value, ok := c.Get(string(key)); ok { if v, ok := value.(T); ok { return v, true } } var t T return t, false}
func ApiError(c *gin.Context, err error) { c.JSON(http.StatusOK, gin.H{ "success": false, "message": err.Error(), })}
func ApiErrorMsg(c *gin.Context, msg string) { c.JSON(http.StatusOK, gin.H{ "success": false, "message": msg, })}
func ApiSuccess(c *gin.Context, data any) { c.JSON(http.StatusOK, gin.H{ "success": true, "message": "", "data": data, })}
func ParseMultipartFormReusable(c *gin.Context) (*multipart.Form, error) { requestBody, err := GetRequestBody(c) if err != nil { return nil, err }
contentType := c.Request.Header.Get("Content-Type") boundary, err := parseBoundary(contentType) if err != nil { return nil, err }
reader := multipart.NewReader(bytes.NewReader(requestBody), boundary) form, err := reader.ReadForm(multipartMemoryLimit()) if err != nil { return nil, err }
// Reset request body c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody)) return form, nil}
func processFormMap(formMap map[string]any, v any) error { jsonData, err := Marshal(formMap) if err != nil { return err }
err = Unmarshal(jsonData, v) if err != nil { return err }
return nil}
func parseFormData(data []byte, v any) error { values, err := url.ParseQuery(string(data)) if err != nil { return err } formMap := make(map[string]any) for key, vals := range values { if len(vals) == 1 { formMap[key] = vals[0] } else { formMap[key] = vals } }
return processFormMap(formMap, v)}
func parseMultipartFormData(c *gin.Context, data []byte, v any) error { contentType := c.Request.Header.Get("Content-Type") boundary, err := parseBoundary(contentType) if err != nil { if errors.Is(err, errBoundaryNotFound) { return Unmarshal(data, v) // Fallback to JSON } return err }
reader := multipart.NewReader(bytes.NewReader(data), boundary) form, err := reader.ReadForm(multipartMemoryLimit()) if err != nil { return err } defer form.RemoveAll() formMap := make(map[string]any) for key, vals := range form.Value { if len(vals) == 1 { formMap[key] = vals[0] } else { formMap[key] = vals } }
return processFormMap(formMap, v)}
var errBoundaryNotFound = errors.New("multipart boundary not found")
// parseBoundary extracts the multipart boundary from the Content-Type header using mime.ParseMediaTypefunc parseBoundary(contentType string) (string, error) { if contentType == "" { return "", errBoundaryNotFound } // Boundary-UUID / boundary-------xxxxxx _, params, err := mime.ParseMediaType(contentType) if err != nil { return "", err } boundary, ok := params["boundary"] if !ok || boundary == "" { return "", errBoundaryNotFound } return boundary, nil}
// multipartMemoryLimit returns the configured multipart memory limit in bytesfunc multipartMemoryLimit() int64 { limitMB := constant.MaxFileDownloadMB if limitMB <= 0 { limitMB = 32 } return int64(limitMB) << 20}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package common
import ( "time")
func SafeSendBool(ch chan bool, value bool) (closed bool) { defer func() { // Recover from panic if one occured. A panic would mean the channel was closed. if recover() != nil { closed = true } }()
// This will panic if the channel is closed. ch <- value
// If the code reaches here, then the channel was not closed. return false}
func SafeSendString(ch chan string, value string) (closed bool) { defer func() { // Recover from panic if one occured. A panic would mean the channel was closed. if recover() != nil { closed = true } }()
// This will panic if the channel is closed. ch <- value
// If the code reaches here, then the channel was not closed. return false}
// SafeSendStringTimeout send, return true, else return falsefunc SafeSendStringTimeout(ch chan string, value string, timeout int) (closed bool) { defer func() { // Recover from panic if one occured. A panic would mean the channel was closed. if recover() != nil { closed = false } }()
// This will panic if the channel is closed. select { case ch <- value: return true case <-time.After(time.Duration(timeout) * time.Second): return false }}12345678910111213141516171819202122232425package common
import ( "context" "fmt" "math"
"github.com/bytedance/gopkg/util/gopool")
var relayGoPool gopool.Pool
func init() { relayGoPool = gopool.NewPool("gopool.RelayPool", math.MaxInt32, gopool.NewConfig()) relayGoPool.SetPanicHandler(func(ctx context.Context, i interface{}) { if stopChan, ok := ctx.Value("stop_chan").(chan bool); ok { SafeSendBool(stopChan, true) } SysError(fmt.Sprintf("panic in gopool.RelayPool: %v", i)) })}
func RelayCtxGo(ctx context.Context, f func()) { relayGoPool.CtxGo(ctx, f)}12345678910111213141516171819202122232425262728293031323334package common
import ( "crypto/hmac" "crypto/sha1" "crypto/sha256" "encoding/hex")
func Sha256Raw(data []byte) []byte { h := sha256.New() h.Write(data) return h.Sum(nil)}
func Sha1Raw(data []byte) []byte { h := sha1.New() h.Write(data) return h.Sum(nil)}
func Sha1(data []byte) string { return hex.EncodeToString(Sha1Raw(data))}
func HmacSha256Raw(message, key []byte) []byte { h := hmac.New(sha256.New, key) h.Write(message) return h.Sum(nil)}
func HmacSha256(message, key string) string { return hex.EncodeToString(HmacSha256Raw([]byte(message), []byte(key)))}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144package common
import ( "flag" "fmt" "log" "os" "path/filepath" "strconv" "strings" "time"
"github.com/QuantumNous/new-api/constant")
var ( Port = flag.Int("port", 3000, "the listening port") PrintVersion = flag.Bool("version", false, "print version and exit") PrintHelp = flag.Bool("help", false, "print help and exit") LogDir = flag.String("log-dir", "./logs", "specify the log directory"))
func printHelp() { fmt.Println("NewAPI(Based OneAPI) " + Version + " - The next-generation LLM gateway and AI asset management system supports multiple languages.") fmt.Println("Original Project: OneAPI by JustSong - https://github.com/songquanpeng/one-api") fmt.Println("Maintainer: QuantumNous - https://github.com/QuantumNous/new-api") fmt.Println("Usage: newapi [--port <port>] [--log-dir <log directory>] [--version] [--help]")}
func InitEnv() { flag.Parse()
envVersion := os.Getenv("VERSION") if envVersion != "" { Version = envVersion }
if *PrintVersion { fmt.Println(Version) os.Exit(0) }
if *PrintHelp { printHelp() os.Exit(0) }
if os.Getenv("SESSION_SECRET") != "" { ss := os.Getenv("SESSION_SECRET") if ss == "random_string" { log.Println("WARNING: SESSION_SECRET is set to the default value 'random_string', please change it to a random string.") log.Println("警告:SESSION_SECRET被设置为默认值'random_string',请修改为随机字符串。") log.Fatal("Please set SESSION_SECRET to a random string.") } else { SessionSecret = ss } } if os.Getenv("CRYPTO_SECRET") != "" { CryptoSecret = os.Getenv("CRYPTO_SECRET") } else { CryptoSecret = SessionSecret } if os.Getenv("SQLITE_PATH") != "" { SQLitePath = os.Getenv("SQLITE_PATH") } if *LogDir != "" { var err error *LogDir, err = filepath.Abs(*LogDir) if err != nil { log.Fatal(err) } if _, err := os.Stat(*LogDir); os.IsNotExist(err) { err = os.Mkdir(*LogDir, 0777) if err != nil { log.Fatal(err) } } }
// Initialize variables from constants.go that were using environment variables DebugEnabled = os.Getenv("DEBUG") == "true" MemoryCacheEnabled = os.Getenv("MEMORY_CACHE_ENABLED") == "true" IsMasterNode = os.Getenv("NODE_TYPE") != "slave"
// Parse requestInterval and set RequestInterval requestInterval, _ = strconv.Atoi(os.Getenv("POLLING_INTERVAL")) RequestInterval = time.Duration(requestInterval) * time.Second
// Initialize variables with GetEnvOrDefault SyncFrequency = GetEnvOrDefault("SYNC_FREQUENCY", 60) BatchUpdateInterval = GetEnvOrDefault("BATCH_UPDATE_INTERVAL", 5) RelayTimeout = GetEnvOrDefault("RELAY_TIMEOUT", 0)
// Initialize string variables with GetEnvOrDefaultString GeminiSafetySetting = GetEnvOrDefaultString("GEMINI_SAFETY_SETTING", "BLOCK_NONE") CohereSafetySetting = GetEnvOrDefaultString("COHERE_SAFETY_SETTING", "NONE")
// Initialize rate limit variables GlobalApiRateLimitEnable = GetEnvOrDefaultBool("GLOBAL_API_RATE_LIMIT_ENABLE", true) GlobalApiRateLimitNum = GetEnvOrDefault("GLOBAL_API_RATE_LIMIT", 180) GlobalApiRateLimitDuration = int64(GetEnvOrDefault("GLOBAL_API_RATE_LIMIT_DURATION", 180))
GlobalWebRateLimitEnable = GetEnvOrDefaultBool("GLOBAL_WEB_RATE_LIMIT_ENABLE", true) GlobalWebRateLimitNum = GetEnvOrDefault("GLOBAL_WEB_RATE_LIMIT", 60) GlobalWebRateLimitDuration = int64(GetEnvOrDefault("GLOBAL_WEB_RATE_LIMIT_DURATION", 180))
CriticalRateLimitEnable = GetEnvOrDefaultBool("CRITICAL_RATE_LIMIT_ENABLE", true) CriticalRateLimitNum = GetEnvOrDefault("CRITICAL_RATE_LIMIT", 20) CriticalRateLimitDuration = int64(GetEnvOrDefault("CRITICAL_RATE_LIMIT_DURATION", 20*60)) initConstantEnv()}
func initConstantEnv() { constant.StreamingTimeout = GetEnvOrDefault("STREAMING_TIMEOUT", 300) constant.DifyDebug = GetEnvOrDefaultBool("DIFY_DEBUG", true) constant.MaxFileDownloadMB = GetEnvOrDefault("MAX_FILE_DOWNLOAD_MB", 20) // ForceStreamOption 覆盖请求参数,强制返回usage信息 constant.ForceStreamOption = GetEnvOrDefaultBool("FORCE_STREAM_OPTION", true) constant.CountToken = GetEnvOrDefaultBool("CountToken", true) constant.GetMediaToken = GetEnvOrDefaultBool("GET_MEDIA_TOKEN", true) constant.GetMediaTokenNotStream = GetEnvOrDefaultBool("GET_MEDIA_TOKEN_NOT_STREAM", false) constant.UpdateTask = GetEnvOrDefaultBool("UPDATE_TASK", true) constant.AzureDefaultAPIVersion = GetEnvOrDefaultString("AZURE_DEFAULT_API_VERSION", "2025-04-01-preview") constant.GeminiVisionMaxImageNum = GetEnvOrDefault("GEMINI_VISION_MAX_IMAGE_NUM", 16) constant.NotifyLimitCount = GetEnvOrDefault("NOTIFY_LIMIT_COUNT", 2) constant.NotificationLimitDurationMinute = GetEnvOrDefault("NOTIFICATION_LIMIT_DURATION_MINUTE", 10) // GenerateDefaultToken 是否生成初始令牌,默认关闭。 constant.GenerateDefaultToken = GetEnvOrDefaultBool("GENERATE_DEFAULT_TOKEN", false) // 是否启用错误日志 constant.ErrorLogEnabled = GetEnvOrDefaultBool("ERROR_LOG_ENABLED", false)
soraPatchStr := GetEnvOrDefaultString("TASK_PRICE_PATCH", "") if soraPatchStr != "" { var taskPricePatches []string soraPatches := strings.Split(soraPatchStr, ",") for _, patch := range soraPatches { trimmedPatch := strings.TrimSpace(patch) if trimmedPatch != "" { taskPricePatches = append(taskPricePatches, trimmedPatch) } } constant.TaskPricePatches = taskPricePatches }}12345678910111213141516171819202122package common
import "net"
func IsPrivateIP(ip net.IP) bool { if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() { return true }
private := []net.IPNet{ {IP: net.IPv4(10, 0, 0, 0), Mask: net.CIDRMask(8, 32)}, {IP: net.IPv4(172, 16, 0, 0), Mask: net.CIDRMask(12, 32)}, {IP: net.IPv4(192, 168, 0, 0), Mask: net.CIDRMask(16, 32)}, }
for _, privateNet := range private { if privateNet.Contains(ip) { return true } } return false}123456789101112131415161718192021222324252627282930313233343536373839404142434445package common
import ( "bytes" "encoding/json" "io")
func Unmarshal(data []byte, v any) error { return json.Unmarshal(data, v)}
func UnmarshalJsonStr(data string, v any) error { return json.Unmarshal(StringToByteSlice(data), v)}
func DecodeJson(reader io.Reader, v any) error { return json.NewDecoder(reader).Decode(v)}
func Marshal(v any) ([]byte, error) { return json.Marshal(v)}
func GetJsonType(data json.RawMessage) string { data = bytes.TrimSpace(data) if len(data) == 0 { return "unknown" } firstChar := bytes.TrimSpace(data)[0] switch firstChar { case '{': return "object" case '[': return "array" case '"': return "string" case 't', 'f': return "boolean" case 'n': return "null" default: return "number" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990package limiter
import ( "context" _ "embed" "fmt" "sync"
"github.com/QuantumNous/new-api/common" "github.com/go-redis/redis/v8")
//go:embed lua/rate_limit.luavar rateLimitScript string
type RedisLimiter struct { client *redis.Client limitScriptSHA string}
var ( instance *RedisLimiter once sync.Once)
func New(ctx context.Context, r *redis.Client) *RedisLimiter { once.Do(func() { // 预加载脚本 limitSHA, err := r.ScriptLoad(ctx, rateLimitScript).Result() if err != nil { common.SysLog(fmt.Sprintf("Failed to load rate limit script: %v", err)) } instance = &RedisLimiter{ client: r, limitScriptSHA: limitSHA, } })
return instance}
func (rl *RedisLimiter) Allow(ctx context.Context, key string, opts ...Option) (bool, error) { // 默认配置 config := &Config{ Capacity: 10, Rate: 1, Requested: 1, }
// 应用选项模式 for _, opt := range opts { opt(config) }
// 执行限流 result, err := rl.client.EvalSha( ctx, rl.limitScriptSHA, []string{key}, config.Requested, config.Rate, config.Capacity, ).Int()
if err != nil { return false, fmt.Errorf("rate limit failed: %w", err) } return result == 1, nil}
// Config 配置选项模式type Config struct { Capacity int64 Rate int64 Requested int64}
type Option func(*Config)
func WithCapacity(c int64) Option { return func(cfg *Config) { cfg.Capacity = c }}
func WithRate(r int64) Option { return func(cfg *Config) { cfg.Rate = r }}
func WithRequested(n int64) Option { return func(cfg *Config) { cfg.Requested = n }}1234567891011121314151617181920212223242526272829303132333435363738394041424344-- 令牌桶限流器-- KEYS[1]: 限流器唯一标识-- ARGV[1]: 请求令牌数 (通常为1)-- ARGV[2]: 令牌生成速率 (每秒)-- ARGV[3]: 桶容量
local key = KEYS[1]local requested = tonumber(ARGV[1])local rate = tonumber(ARGV[2])local capacity = tonumber(ARGV[3])
-- 获取当前时间(Redis服务器时间)local now = redis.call('TIME')local nowInSeconds = tonumber(now[1])
-- 获取桶状态local bucket = redis.call('HMGET', key, 'tokens', 'last_time')local tokens = tonumber(bucket[1])local last_time = tonumber(bucket[2])
-- 初始化桶(首次请求或过期)if not tokens or not last_time then tokens = capacity last_time = nowInSecondselse -- 计算新增令牌 local elapsed = nowInSeconds - last_time local add_tokens = elapsed * rate tokens = math.min(capacity, tokens + add_tokens) last_time = nowInSecondsend
-- 判断是否允许请求local allowed = falseif tokens >= requested then tokens = tokens - requested allowed = trueend
---- 更新桶状态并设置过期时间redis.call('HMSET', key, 'tokens', tokens, 'last_time', last_time)--redis.call('EXPIRE', key, math.ceil(capacity / rate) + 60) -- 适当延长过期时间
return allowed and 1 or 0123456789101112131415161718192021222324252627282930313233343536373839404142package common
import "strings"
var ( // OpenAIResponseOnlyModels is a list of models that are only available for OpenAI responses. OpenAIResponseOnlyModels = []string{ "o3-pro", "o3-deep-research", "o4-mini-deep-research", } ImageGenerationModels = []string{ "dall-e-3", "dall-e-2", "gpt-image-1", "prefix:imagen-", "flux-", "flux.1-", })
func IsOpenAIResponseOnlyModel(modelName string) bool { for _, m := range OpenAIResponseOnlyModels { if strings.Contains(modelName, m) { return true } } return false}
func IsImageGenerationModel(modelName string) bool { modelName = strings.ToLower(modelName) for _, m := range ImageGenerationModels { if strings.Contains(modelName, m) { return true } if strings.HasPrefix(m, "prefix:") && strings.HasPrefix(modelName, strings.TrimPrefix(m, "prefix:")) { return true } } return false}.dockerignoreAdded+9
.env.exampleAdded+76
.gitattributesAdded+3
.github/FUNDING.ymlAdded+12
.github/ISSUE_TEMPLATE/bug_report.mdAdded+26
.github/ISSUE_TEMPLATE/bug_report_en.mdAdded+26
.github/ISSUE_TEMPLATE/config.ymlAdded+5
.github/ISSUE_TEMPLATE/feature_request.mdAdded+21
.github/ISSUE_TEMPLATE/feature_request_en.mdAdded+22
.github/PULL_REQUEST_TEMPLATE/pull_request_template.mdAdded+15
.github/workflows/docker-image-alpha.ymlAdded+151
.github/workflows/docker-image-arm64.ymlAdded+138
.github/workflows/electron-build.ymlAdded+141
.github/workflows/release.ymlAdded+142
.github/workflows/sync-to-gitee.ymlAdded+91
.gitignoreAdded+23
DockerfileAdded+44
Dockerfile.hfAdded+44
LICENSEAdded+103
README.en.mdAdded+447
README.fr.mdAdded+441
README.ja.mdAdded+450
README.mdAdded+459
VERSIONAdded
bin/migration_v0.2-v0.3.sqlAdded+6
bin/migration_v0.3-v0.4.sqlAdded+17
bin/time_test.shAdded+40
common/api_type.goAdded+81
common/audio.goAdded+296
common/constants.goAdded+204
common/copy.goAdded+19
common/crypto.goAdded+32
common/custom-event.goAdded+87
common/database.goAdded+15
common/email-outlook-auth.goAdded+40
common/email.goAdded+93
common/embed-file-system.goAdded+43
common/endpoint_defaults.goAdded+33
common/endpoint_type.goAdded+43
common/env.goAdded+38
common/gin.goAdded+234
common/go-channel.goAdded+53
common/gopool.goAdded+25
common/hash.goAdded+34
common/init.goAdded+144
common/ip.goAdded+22
common/json.goAdded+45
common/limiter/limiter.goAdded+90
common/limiter/lua/rate_limit.luaAdded+44
common/model.goAdded+42