diff --git a/.github/workflows/docker-image-en.yml b/.github/workflows/docker-image-en.yml deleted file mode 100644 index 30cd0e38..00000000 --- a/.github/workflows/docker-image-en.yml +++ /dev/null @@ -1,64 +0,0 @@ -name: Publish Docker image (English) - -on: - push: - tags: - - 'v*.*.*' - workflow_dispatch: - inputs: - name: - description: 'reason' - required: false -jobs: - push_to_registries: - name: Push Docker image to multiple registries - runs-on: ubuntu-latest - permissions: - packages: write - contents: read - steps: - - name: Check out the repo - uses: actions/checkout@v3 - - - name: Check repository URL - run: | - REPO_URL=$(git config --get remote.origin.url) - if [[ $REPO_URL == *"pro" ]]; then - exit 1 - fi - - - name: Save version info - run: | - git describe --tags > VERSION - - - name: Translate - run: | - python ./i18n/translate.py --repository_path . --json_file_path ./i18n/en.json - - - name: Set up QEMU - uses: docker/setup-qemu-action@v2 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Log in to Docker Hub - uses: docker/login-action@v2 - with: - username: ${{ secrets.DOCKERHUB_USERNAME }} - password: ${{ secrets.DOCKERHUB_TOKEN }} - - - name: Extract metadata (tags, labels) for Docker - id: meta - uses: docker/metadata-action@v4 - with: - images: | - justsong/one-api-en - - - name: Build and push Docker images - uses: docker/build-push-action@v3 - with: - context: . - platforms: linux/amd64,linux/arm64 - push: true - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} \ No newline at end of file diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 56f1d6ad..01c58947 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -32,10 +32,10 @@ jobs: git describe --tags > VERSION - name: Set up QEMU - uses: docker/setup-qemu-action@v2 + uses: docker/setup-qemu-action@v3 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@v3 - name: Log in to Docker Hub uses: docker/login-action@v2 @@ -55,14 +55,16 @@ jobs: uses: docker/metadata-action@v4 with: images: | - justsong/one-api - ghcr.io/${{ github.repository }} + ${{ contains(github.ref, 'alpha') && 'justsong/one-api-alpha' || 'justsong/one-api' }} + ${{ contains(github.ref, 'alpha') && format('ghcr.io/{0}-alpha', github.repository) || format('ghcr.io/{0}', github.repository) }} - name: Build and push Docker images uses: docker/build-push-action@v3 with: context: . - platforms: linux/amd64,linux/arm64 + platforms: ${{ contains(github.ref, 'alpha') && 'linux/amd64' || 'linux/amd64,linux/arm64' }} push: true tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} \ No newline at end of file + labels: ${{ steps.meta.outputs.labels }} + build-args: | + TARGETARCH=${{ startsWith(matrix.platform, 'linux/arm64') && 'arm64' || 'amd64' }} \ No newline at end of file diff --git a/.github/workflows/linux-release.yml b/.github/workflows/linux-release.yml index 161c41e3..08639b15 100644 --- a/.github/workflows/linux-release.yml +++ b/.github/workflows/linux-release.yml @@ -7,6 +7,7 @@ on: tags: - 'v*.*.*' - '!*-alpha*' + - '!*-preview*' workflow_dispatch: inputs: name: diff --git a/.github/workflows/macos-release.yml b/.github/workflows/macos-release.yml index 94b3e47b..74d2aa0a 100644 --- a/.github/workflows/macos-release.yml +++ b/.github/workflows/macos-release.yml @@ -7,6 +7,7 @@ on: tags: - 'v*.*.*' - '!*-alpha*' + - '!*-preview*' workflow_dispatch: inputs: name: diff --git a/.github/workflows/windows-release.yml b/.github/workflows/windows-release.yml index 18641ae8..aed7bb10 100644 --- a/.github/workflows/windows-release.yml +++ b/.github/workflows/windows-release.yml @@ -7,6 +7,7 @@ on: tags: - 'v*.*.*' - '!*-alpha*' + - '!*-preview*' workflow_dispatch: inputs: name: diff --git a/.gitignore b/.gitignore index 0cedb4b4..e1e018ea 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,5 @@ data cmd.md .env /one-api +temp +.DS_Store \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index ade561e4..fc43cde2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,41 +4,45 @@ WORKDIR /web COPY ./VERSION . COPY ./web . -WORKDIR /web/default -RUN npm install -RUN DISABLE_ESLINT_PLUGIN='true' REACT_APP_VERSION=$(cat VERSION) npm run build +RUN npm install --prefix /web/default & \ + npm install --prefix /web/berry & \ + npm install --prefix /web/air & \ + wait -WORKDIR /web/berry -RUN npm install -RUN DISABLE_ESLINT_PLUGIN='true' REACT_APP_VERSION=$(cat VERSION) npm run build - -WORKDIR /web/air -RUN npm install -RUN DISABLE_ESLINT_PLUGIN='true' REACT_APP_VERSION=$(cat VERSION) npm run build +RUN DISABLE_ESLINT_PLUGIN='true' REACT_APP_VERSION=$(cat ./VERSION) npm run build --prefix /web/default & \ + DISABLE_ESLINT_PLUGIN='true' REACT_APP_VERSION=$(cat ./VERSION) npm run build --prefix /web/berry & \ + DISABLE_ESLINT_PLUGIN='true' REACT_APP_VERSION=$(cat ./VERSION) npm run build --prefix /web/air & \ + wait FROM golang:alpine AS builder2 -RUN apk add --no-cache g++ +RUN apk add --no-cache \ + gcc \ + musl-dev \ + sqlite-dev \ + build-base ENV GO111MODULE=on \ CGO_ENABLED=1 \ - GOOS=linux + GOOS=linux \ + GOARCH=$TARGETARCH WORKDIR /build + ADD go.mod go.sum ./ RUN go mod download + COPY . . COPY --from=builder /web/build ./web/build -RUN go build -trimpath -ldflags "-s -w -X 'github.com/songquanpeng/one-api/common.Version=$(cat VERSION)' -extldflags '-static'" -o one-api -FROM alpine +RUN go build -trimpath -ldflags "-s -w -X 'github.com/songquanpeng/one-api/common.Version=$(cat VERSION)' -linkmode external -extldflags '-static'" -o one-api -RUN apk update \ - && apk upgrade \ - && apk add --no-cache ca-certificates tzdata \ - && update-ca-certificates 2>/dev/null || true +FROM alpine:latest + +RUN apk add --no-cache ca-certificates tzdata COPY --from=builder2 /build/one-api / + EXPOSE 3000 WORKDIR /data ENTRYPOINT ["/one-api"] \ No newline at end of file diff --git a/README.en.md b/README.en.md index c9fdbbc8..61864241 100644 --- a/README.en.md +++ b/README.en.md @@ -52,8 +52,6 @@ _✨ Access all LLM through the standard OpenAI API format, easy to deploy & use > **Warning**: This README is translated by ChatGPT. Please feel free to submit a PR if you find any translation errors. -> **Warning**: The Docker image for English version is `justsong/one-api-en`. - > **Note**: The latest image pulled from Docker may be an `alpha` release. Specify the version manually if you require stability. ## Features @@ -89,7 +87,9 @@ _✨ Access all LLM through the standard OpenAI API format, easy to deploy & use ## Deployment ### Docker Deployment -Deployment command: `docker run --name one-api -d --restart always -p 3000:3000 -e TZ=Asia/Shanghai -v /home/ubuntu/data/one-api:/data justsong/one-api-en` + +Deployment command: +`docker run --name one-api -d --restart always -p 3000:3000 -e TZ=Asia/Shanghai -v /home/ubuntu/data/one-api:/data justsong/one-api` Update command: `docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtower -cR` @@ -315,6 +315,7 @@ If the channel ID is not provided, load balancing will be used to distribute the * [FastGPT](https://github.com/labring/FastGPT): Knowledge question answering system based on the LLM * [VChart](https://github.com/VisActor/VChart): More than just a cross-platform charting library, but also an expressive data storyteller. * [VMind](https://github.com/VisActor/VMind): Not just automatic, but also fantastic. Open-source solution for intelligent visualization. +* * [CherryStudio](https://github.com/CherryHQ/cherry-studio): A cross-platform AI client that integrates multiple service providers and supports local knowledge base management. ## Note This project is an open-source project. Please use it in compliance with OpenAI's [Terms of Use](https://openai.com/policies/terms-of-use) and **applicable laws and regulations**. It must not be used for illegal purposes. diff --git a/README.ja.md b/README.ja.md index c15915ec..38080468 100644 --- a/README.ja.md +++ b/README.ja.md @@ -52,8 +52,6 @@ _✨ 標準的な OpenAI API フォーマットを通じてすべての LLM に > **警告**: この README は ChatGPT によって翻訳されています。翻訳ミスを発見した場合は遠慮なく PR を投稿してください。 -> **警告**: 英語版の Docker イメージは `justsong/one-api-en` です。 - > **注**: Docker からプルされた最新のイメージは、`alpha` リリースかもしれません。安定性が必要な場合は、手動でバージョンを指定してください。 ## 特徴 @@ -89,7 +87,9 @@ _✨ 標準的な OpenAI API フォーマットを通じてすべての LLM に ## デプロイメント ### Docker デプロイメント -デプロイコマンド: `docker run --name one-api -d --restart always -p 3000:3000 -e TZ=Asia/Shanghai -v /home/ubuntu/data/one-api:/data justsong/one-api-en`。 + +デプロイコマンド: +`docker run --name one-api -d --restart always -p 3000:3000 -e TZ=Asia/Shanghai -v /home/ubuntu/data/one-api:/data justsong/one-api`。 コマンドを更新する: `docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrr/watchtower -cR`。 @@ -287,8 +287,8 @@ graph LR + インターフェイスアドレスと API Key が正しいか再確認してください。 ## 関連プロジェクト -[FastGPT](https://github.com/labring/FastGPT): LLM に基づく知識質問応答システム - +* [FastGPT](https://github.com/labring/FastGPT): LLM に基づく知識質問応答システム +* [CherryStudio](https://github.com/CherryHQ/cherry-studio): マルチプラットフォーム対応のAIクライアント。複数のサービスプロバイダーを統合管理し、ローカル知識ベースをサポートします。 ## 注 本プロジェクトはオープンソースプロジェクトです。OpenAI の[利用規約](https://openai.com/policies/terms-of-use)および**適用される法令**を遵守してご利用ください。違法な目的での利用はご遠慮ください。 diff --git a/README.md b/README.md index 853ec067..2a3d3453 100644 --- a/README.md +++ b/README.md @@ -56,8 +56,12 @@ _✨ 通过标准的 OpenAI API 格式访问所有的大模型,开箱即用 > > 根据[《生成式人工智能服务管理暂行办法》](http://www.cac.gov.cn/2023-07/13/c_1690898327029107.htm)的要求,请勿对中国地区公众提供一切未经备案的生成式人工智能服务。 -> [!WARNING] -> 使用 Docker 拉取的最新镜像可能是 `alpha` 版本,如果追求稳定性请手动指定版本。 +> [!NOTE] +> 稳定版 / 预览版镜像地址:[justsong/one-api](https://hub.docker.com/repository/docker/justsong/one-api) +> 或者 [ghcr.io/songquanpeng/one-api](https://github.com/songquanpeng/one-api/pkgs/container/one-api) +> +> alpha 版镜像地址:[justsong/one-api-alpha](https://hub.docker.com/repository/docker/justsong/one-api-alpha) +> 或者 [ghcr.io/songquanpeng/one-api-alpha](https://github.com/songquanpeng/one-api/pkgs/container/one-api-alpha) > [!WARNING] > 使用 root 用户初次登录系统后,务必修改默认密码 `123456`! @@ -89,7 +93,7 @@ _✨ 通过标准的 OpenAI API 格式访问所有的大模型,开箱即用 + [x] [DeepL](https://www.deepl.com/) + [x] [together.ai](https://www.together.ai/) + [x] [novita.ai](https://www.novita.ai/) - + [x] [硅基流动 SiliconCloud](https://siliconflow.cn/siliconcloud) + + [x] [硅基流动 SiliconCloud](https://cloud.siliconflow.cn/i/rKXmRobW) + [x] [xAI](https://x.ai/) 2. 支持配置镜像以及众多[第三方代理服务](https://iamazing.cn/page/openai-api-third-party-services)。 3. 支持通过**负载均衡**的方式访问多个渠道。 @@ -410,6 +414,7 @@ graph LR 27. `INITIAL_ROOT_TOKEN`:如果设置了该值,则在系统首次启动时会自动创建一个值为该环境变量值的 root 用户令牌。 28. `INITIAL_ROOT_ACCESS_TOKEN`:如果设置了该值,则在系统首次启动时会自动创建一个值为该环境变量的 root 用户创建系统管理令牌。 29. `ENFORCE_INCLUDE_USAGE`:是否强制在 stream 模型下返回 usage,默认不开启,可选值为 `true` 和 `false`。 +30. `TEST_PROMPT`:测试模型时的用户 prompt,默认为 `Print your model name exactly and do not output without any other text.`。 ### 命令行参数 1. `--port `: 指定服务器监听的端口号,默认为 `3000`。 @@ -464,6 +469,7 @@ https://openai.justsong.cn * [ChatGPT Next Web](https://github.com/Yidadaa/ChatGPT-Next-Web): 一键拥有你自己的跨平台 ChatGPT 应用 * [VChart](https://github.com/VisActor/VChart): 不只是开箱即用的多端图表库,更是生动灵活的数据故事讲述者。 * [VMind](https://github.com/VisActor/VMind): 不仅自动,还很智能。开源智能可视化解决方案。 +* [CherryStudio](https://github.com/CherryHQ/cherry-studio): 全平台支持的AI客户端, 多服务商集成管理、本地知识库支持。 ## 注意 diff --git a/common/config/config.go b/common/config/config.go index 2eb894ef..34b00d65 100644 --- a/common/config/config.go +++ b/common/config/config.go @@ -1,13 +1,14 @@ package config import ( - "github.com/songquanpeng/one-api/common/env" "os" "strconv" "strings" "sync" "time" + "github.com/songquanpeng/one-api/common/env" + "github.com/google/uuid" ) @@ -125,10 +126,10 @@ var ValidThemes = map[string]bool{ // All duration's unit is seconds // Shouldn't larger then RateLimitKeyExpirationDuration var ( - GlobalApiRateLimitNum = env.Int("GLOBAL_API_RATE_LIMIT", 240) + GlobalApiRateLimitNum = env.Int("GLOBAL_API_RATE_LIMIT", 480) GlobalApiRateLimitDuration int64 = 3 * 60 - GlobalWebRateLimitNum = env.Int("GLOBAL_WEB_RATE_LIMIT", 120) + GlobalWebRateLimitNum = env.Int("GLOBAL_WEB_RATE_LIMIT", 240) GlobalWebRateLimitDuration int64 = 3 * 60 UploadRateLimitNum = 10 @@ -162,3 +163,4 @@ var UserContentRequestProxy = env.String("USER_CONTENT_REQUEST_PROXY", "") var UserContentRequestTimeout = env.Int("USER_CONTENT_REQUEST_TIMEOUT", 30) var EnforceIncludeUsage = env.Bool("ENFORCE_INCLUDE_USAGE", false) +var TestPrompt = env.String("TEST_PROMPT", "Print your model name exactly and do not output without any other text.") diff --git a/common/gin.go b/common/gin.go index 815b4ee5..e3281fee 100644 --- a/common/gin.go +++ b/common/gin.go @@ -3,10 +3,11 @@ package common import ( "bytes" "encoding/json" - "github.com/gin-gonic/gin" - "github.com/songquanpeng/one-api/common/ctxkey" "io" "strings" + + "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common/ctxkey" ) func GetRequestBody(c *gin.Context) ([]byte, error) { @@ -31,7 +32,6 @@ func UnmarshalBodyReusable(c *gin.Context, v any) error { contentType := c.Request.Header.Get("Content-Type") if strings.HasPrefix(contentType, "application/json") { err = json.Unmarshal(requestBody, &v) - c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody)) } else { c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody)) err = c.ShouldBind(&v) @@ -40,6 +40,7 @@ func UnmarshalBodyReusable(c *gin.Context, v any) error { return err } // Reset request body + c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody)) return nil } diff --git a/common/helper/helper.go b/common/helper/helper.go index df7b0a5f..65f4fd29 100644 --- a/common/helper/helper.go +++ b/common/helper/helper.go @@ -1,9 +1,8 @@ package helper import ( + "context" "fmt" - "github.com/gin-gonic/gin" - "github.com/songquanpeng/one-api/common/random" "html/template" "log" "net" @@ -11,6 +10,10 @@ import ( "runtime" "strconv" "strings" + + "github.com/gin-gonic/gin" + + "github.com/songquanpeng/one-api/common/random" ) func OpenBrowser(url string) { @@ -106,6 +109,18 @@ func GenRequestID() string { return GetTimeString() + random.GetRandomNumberString(8) } +func SetRequestID(ctx context.Context, id string) context.Context { + return context.WithValue(ctx, RequestIdKey, id) +} + +func GetRequestID(ctx context.Context) string { + rawRequestId := ctx.Value(RequestIdKey) + if rawRequestId == nil { + return "" + } + return rawRequestId.(string) +} + func GetResponseID(c *gin.Context) string { logID := c.GetString(RequestIdKey) return fmt.Sprintf("chatcmpl-%s", logID) diff --git a/common/helper/time.go b/common/helper/time.go index 302746db..f0bc6021 100644 --- a/common/helper/time.go +++ b/common/helper/time.go @@ -13,3 +13,8 @@ func GetTimeString() string { now := time.Now() return fmt.Sprintf("%s%d", now.Format("20060102150405"), now.UnixNano()%1e9) } + +// CalcElapsedTime return the elapsed time in milliseconds (ms) +func CalcElapsedTime(start time.Time) int64 { + return time.Now().Sub(start).Milliseconds() +} diff --git a/common/i18n/i18n.go b/common/i18n/i18n.go new file mode 100644 index 00000000..dfad6eac --- /dev/null +++ b/common/i18n/i18n.go @@ -0,0 +1,72 @@ +package i18n + +import ( + "embed" + "encoding/json" + "strings" + + "github.com/gin-gonic/gin" +) + +//go:embed locales/*.json +var localesFS embed.FS + +var ( + translations = make(map[string]map[string]string) + defaultLang = "en" + ContextKey = "i18n" +) + +// Init loads all translation files from embedded filesystem +func Init() error { + entries, err := localesFS.ReadDir("locales") + if err != nil { + return err + } + + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") { + continue + } + + langCode := strings.TrimSuffix(entry.Name(), ".json") + content, err := localesFS.ReadFile("locales/" + entry.Name()) + if err != nil { + return err + } + + var translation map[string]string + if err := json.Unmarshal(content, &translation); err != nil { + return err + } + translations[langCode] = translation + } + + return nil +} + +func GetLang(c *gin.Context) string { + rawLang, ok := c.Get(ContextKey) + if !ok { + return defaultLang + } + lang, _ := rawLang.(string) + if lang != "" { + return lang + } + return defaultLang +} + +func Translate(c *gin.Context, message string) string { + lang := GetLang(c) + return translateHelper(lang, message) +} + +func translateHelper(lang, message string) string { + if trans, ok := translations[lang]; ok { + if translated, exists := trans[message]; exists { + return translated + } + } + return message +} diff --git a/common/i18n/locales/en.json b/common/i18n/locales/en.json new file mode 100644 index 00000000..4b24dea7 --- /dev/null +++ b/common/i18n/locales/en.json @@ -0,0 +1,5 @@ +{ + "invalid_input": "Invalid input, please check your input", + "send_email_failed": "failed to send email: ", + "invalid_parameter": "invalid parameter" +} diff --git a/common/i18n/locales/zh-CN.json b/common/i18n/locales/zh-CN.json new file mode 100644 index 00000000..805d5c5a --- /dev/null +++ b/common/i18n/locales/zh-CN.json @@ -0,0 +1,5 @@ +{ + "invalid_input": "无效的输入,请检查您的输入", + "send_email_failed": "发送邮件失败:", + "invalid_parameter": "无效的参数" +} diff --git a/common/logger/logger.go b/common/logger/logger.go index d1022932..b5348033 100644 --- a/common/logger/logger.go +++ b/common/logger/logger.go @@ -7,19 +7,25 @@ import ( "log" "os" "path/filepath" + "runtime" + "strings" "sync" "time" "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/helper" ) +type loggerLevel string + const ( - loggerDEBUG = "DEBUG" - loggerINFO = "INFO" - loggerWarn = "WARN" - loggerError = "ERR" + loggerDEBUG loggerLevel = "DEBUG" + loggerINFO loggerLevel = "INFO" + loggerWarn loggerLevel = "WARN" + loggerError loggerLevel = "ERROR" + loggerFatal loggerLevel = "FATAL" ) var setupLogOnce sync.Once @@ -44,27 +50,34 @@ func SetupLogger() { } func SysLog(s string) { - t := time.Now() - _, _ = fmt.Fprintf(gin.DefaultWriter, "[SYS] %v | %s \n", t.Format("2006/01/02 - 15:04:05"), s) + logHelper(nil, loggerINFO, s) } func SysLogf(format string, a ...any) { - SysLog(fmt.Sprintf(format, a...)) + logHelper(nil, loggerINFO, fmt.Sprintf(format, a...)) +} + +func SysWarn(s string) { + logHelper(nil, loggerWarn, s) +} + +func SysWarnf(format string, a ...any) { + logHelper(nil, loggerWarn, fmt.Sprintf(format, a...)) } func SysError(s string) { - t := time.Now() - _, _ = fmt.Fprintf(gin.DefaultErrorWriter, "[SYS] %v | %s \n", t.Format("2006/01/02 - 15:04:05"), s) + logHelper(nil, loggerError, s) } func SysErrorf(format string, a ...any) { - SysError(fmt.Sprintf(format, a...)) + logHelper(nil, loggerError, fmt.Sprintf(format, a...)) } func Debug(ctx context.Context, msg string) { - if config.DebugEnabled { - logHelper(ctx, loggerDEBUG, msg) + if !config.DebugEnabled { + return } + logHelper(ctx, loggerDEBUG, msg) } func Info(ctx context.Context, msg string) { @@ -80,37 +93,65 @@ func Error(ctx context.Context, msg string) { } func Debugf(ctx context.Context, format string, a ...any) { - Debug(ctx, fmt.Sprintf(format, a...)) + logHelper(ctx, loggerDEBUG, fmt.Sprintf(format, a...)) } func Infof(ctx context.Context, format string, a ...any) { - Info(ctx, fmt.Sprintf(format, a...)) + logHelper(ctx, loggerINFO, fmt.Sprintf(format, a...)) } func Warnf(ctx context.Context, format string, a ...any) { - Warn(ctx, fmt.Sprintf(format, a...)) + logHelper(ctx, loggerWarn, fmt.Sprintf(format, a...)) } func Errorf(ctx context.Context, format string, a ...any) { - Error(ctx, fmt.Sprintf(format, a...)) + logHelper(ctx, loggerError, fmt.Sprintf(format, a...)) } -func logHelper(ctx context.Context, level string, msg string) { +func FatalLog(s string) { + logHelper(nil, loggerFatal, s) +} + +func FatalLogf(format string, a ...any) { + logHelper(nil, loggerFatal, fmt.Sprintf(format, a...)) +} + +func logHelper(ctx context.Context, level loggerLevel, msg string) { writer := gin.DefaultErrorWriter if level == loggerINFO { writer = gin.DefaultWriter } - id := ctx.Value(helper.RequestIdKey) - if id == nil { - id = helper.GenRequestID() + var requestId string + if ctx != nil { + rawRequestId := helper.GetRequestID(ctx) + if rawRequestId != "" { + requestId = fmt.Sprintf(" | %s", rawRequestId) + } } + lineInfo, funcName := getLineInfo() now := time.Now() - _, _ = fmt.Fprintf(writer, "[%s] %v | %s | %s \n", level, now.Format("2006/01/02 - 15:04:05"), id, msg) + _, _ = fmt.Fprintf(writer, "[%s] %v%s%s %s%s \n", level, now.Format("2006/01/02 - 15:04:05"), requestId, lineInfo, funcName, msg) SetupLogger() + if level == loggerFatal { + os.Exit(1) + } } -func FatalLog(v ...any) { - t := time.Now() - _, _ = fmt.Fprintf(gin.DefaultErrorWriter, "[FATAL] %v | %v \n", t.Format("2006/01/02 - 15:04:05"), v) - os.Exit(1) +func getLineInfo() (string, string) { + funcName := "[unknown] " + pc, file, line, ok := runtime.Caller(3) + if ok { + if fn := runtime.FuncForPC(pc); fn != nil { + parts := strings.Split(fn.Name(), ".") + funcName = "[" + parts[len(parts)-1] + "] " + } + } else { + file = "unknown" + line = 0 + } + parts := strings.Split(file, "one-api/") + if len(parts) > 1 { + file = parts[1] + } + return fmt.Sprintf(" | %s:%d", file, line), funcName } diff --git a/common/message/email.go b/common/message/email.go index 187ac8c3..85a83d6d 100644 --- a/common/message/email.go +++ b/common/message/email.go @@ -5,11 +5,13 @@ import ( "crypto/tls" "encoding/base64" "fmt" - "github.com/songquanpeng/one-api/common/config" "net" "net/smtp" "strings" "time" + + "github.com/songquanpeng/one-api/common/config" + "github.com/songquanpeng/one-api/common/logger" ) func shouldAuth() bool { @@ -98,8 +100,12 @@ func SendEmail(subject string, receiver string, content string) error { if err != nil { return err } - } else { - err = smtp.SendMail(addr, auth, config.SMTPAccount, to, mail) + return nil + } + err = smtp.SendMail(addr, auth, config.SMTPAccount, to, mail) + if err != nil && strings.Contains(err.Error(), "short response") { // 部分提供商返回该错误,但实际上邮件已经发送成功 + logger.SysWarnf("short response from SMTP server, return nil instead of error: %s", err.Error()) + return nil } return err } diff --git a/common/message/template.go b/common/message/template.go new file mode 100644 index 00000000..55733725 --- /dev/null +++ b/common/message/template.go @@ -0,0 +1,34 @@ +package message + +import ( + "fmt" + + "github.com/songquanpeng/one-api/common/config" +) + +// EmailTemplate 生成美观的 HTML 邮件内容 +func EmailTemplate(title, content string) string { + return fmt.Sprintf(` + + + + + + + +
+
+

%s

+
+
+ %s +
+
+

此邮件由系统自动发送,请勿直接回复

+

%s

+
+
+ + +`, title, content, config.SystemName) +} diff --git a/controller/auth/github.go b/controller/auth/github.go index 15542655..ecdd183c 100644 --- a/controller/auth/github.go +++ b/controller/auth/github.go @@ -5,16 +5,18 @@ import ( "encoding/json" "errors" "fmt" + "net/http" + "strconv" + "time" + "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/common/random" "github.com/songquanpeng/one-api/controller" "github.com/songquanpeng/one-api/model" - "net/http" - "strconv" - "time" ) type GitHubOAuthResponse struct { @@ -81,6 +83,7 @@ func getGitHubUserInfoByCode(code string) (*GitHubUser, error) { } func GitHubOAuth(c *gin.Context) { + ctx := c.Request.Context() session := sessions.Default(c) state := c.Query("state") if state == "" || session.Get("oauth_state") == nil || state != session.Get("oauth_state").(string) { @@ -136,7 +139,7 @@ func GitHubOAuth(c *gin.Context) { user.Role = model.RoleCommonUser user.Status = model.UserStatusEnabled - if err := user.Insert(0); err != nil { + if err := user.Insert(ctx, 0); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, "message": err.Error(), diff --git a/controller/auth/lark.go b/controller/auth/lark.go index 39088b3c..651d5874 100644 --- a/controller/auth/lark.go +++ b/controller/auth/lark.go @@ -5,15 +5,17 @@ import ( "encoding/json" "errors" "fmt" + "net/http" + "strconv" + "time" + "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/controller" "github.com/songquanpeng/one-api/model" - "net/http" - "strconv" - "time" ) type LarkOAuthResponse struct { @@ -79,6 +81,7 @@ func getLarkUserInfoByCode(code string) (*LarkUser, error) { } func LarkOAuth(c *gin.Context) { + ctx := c.Request.Context() session := sessions.Default(c) state := c.Query("state") if state == "" || session.Get("oauth_state") == nil || state != session.Get("oauth_state").(string) { @@ -125,7 +128,7 @@ func LarkOAuth(c *gin.Context) { user.Role = model.RoleCommonUser user.Status = model.UserStatusEnabled - if err := user.Insert(0); err != nil { + if err := user.Insert(ctx, 0); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, "message": err.Error(), diff --git a/controller/auth/oidc.go b/controller/auth/oidc.go index 7b4ad4b9..1c4eedbe 100644 --- a/controller/auth/oidc.go +++ b/controller/auth/oidc.go @@ -5,15 +5,17 @@ import ( "encoding/json" "errors" "fmt" + "net/http" + "strconv" + "time" + "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/controller" "github.com/songquanpeng/one-api/model" - "net/http" - "strconv" - "time" ) type OidcResponse struct { @@ -87,6 +89,7 @@ func getOidcUserInfoByCode(code string) (*OidcUser, error) { } func OidcAuth(c *gin.Context) { + ctx := c.Request.Context() session := sessions.Default(c) state := c.Query("state") if state == "" || session.Get("oauth_state") == nil || state != session.Get("oauth_state").(string) { @@ -142,7 +145,7 @@ func OidcAuth(c *gin.Context) { } else { user.DisplayName = "OIDC User" } - err := user.Insert(0) + err := user.Insert(ctx, 0) if err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, diff --git a/controller/auth/wechat.go b/controller/auth/wechat.go index a561aec0..9c30b8f0 100644 --- a/controller/auth/wechat.go +++ b/controller/auth/wechat.go @@ -4,14 +4,16 @@ import ( "encoding/json" "errors" "fmt" + "net/http" + "strconv" + "time" + "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/ctxkey" "github.com/songquanpeng/one-api/controller" "github.com/songquanpeng/one-api/model" - "net/http" - "strconv" - "time" ) type wechatLoginResponse struct { @@ -52,6 +54,7 @@ func getWeChatIdByCode(code string) (string, error) { } func WeChatAuth(c *gin.Context) { + ctx := c.Request.Context() if !config.WeChatAuthEnabled { c.JSON(http.StatusOK, gin.H{ "message": "管理员未开启通过微信登录以及注册", @@ -87,7 +90,7 @@ func WeChatAuth(c *gin.Context) { user.Role = model.RoleCommonUser user.Status = model.UserStatusEnabled - if err := user.Insert(0); err != nil { + if err := user.Insert(ctx, 0); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, "message": err.Error(), diff --git a/controller/channel-test.go b/controller/channel-test.go index 971f5382..c24ad971 100644 --- a/controller/channel-test.go +++ b/controller/channel-test.go @@ -2,6 +2,7 @@ package controller import ( "bytes" + "context" "encoding/json" "errors" "fmt" @@ -15,14 +16,17 @@ import ( "time" "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/ctxkey" + "github.com/songquanpeng/one-api/common/helper" "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/common/message" "github.com/songquanpeng/one-api/middleware" "github.com/songquanpeng/one-api/model" "github.com/songquanpeng/one-api/monitor" - relay "github.com/songquanpeng/one-api/relay" + "github.com/songquanpeng/one-api/relay" + "github.com/songquanpeng/one-api/relay/adaptor/openai" "github.com/songquanpeng/one-api/relay/channeltype" "github.com/songquanpeng/one-api/relay/controller" "github.com/songquanpeng/one-api/relay/meta" @@ -35,18 +39,34 @@ func buildTestRequest(model string) *relaymodel.GeneralOpenAIRequest { model = "gpt-3.5-turbo" } testRequest := &relaymodel.GeneralOpenAIRequest{ - MaxTokens: 2, - Model: model, + Model: model, } testMessage := relaymodel.Message{ Role: "user", - Content: "hi", + Content: config.TestPrompt, } testRequest.Messages = append(testRequest.Messages, testMessage) return testRequest } -func testChannel(channel *model.Channel, request *relaymodel.GeneralOpenAIRequest) (err error, openaiErr *relaymodel.Error) { +func parseTestResponse(resp string) (*openai.TextResponse, string, error) { + var response openai.TextResponse + err := json.Unmarshal([]byte(resp), &response) + if err != nil { + return nil, "", err + } + if len(response.Choices) == 0 { + return nil, "", errors.New("response has no choices") + } + stringContent, ok := response.Choices[0].Content.(string) + if !ok { + return nil, "", errors.New("response content is not string") + } + return &response, stringContent, nil +} + +func testChannel(ctx context.Context, channel *model.Channel, request *relaymodel.GeneralOpenAIRequest) (responseMessage string, err error, openaiErr *relaymodel.Error) { + startTime := time.Now() w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Request = &http.Request{ @@ -66,7 +86,7 @@ func testChannel(channel *model.Channel, request *relaymodel.GeneralOpenAIReques apiType := channeltype.ToAPIType(channel.Type) adaptor := relay.GetAdaptor(apiType) if adaptor == nil { - return fmt.Errorf("invalid api type: %d, adaptor is nil", apiType), nil + return "", fmt.Errorf("invalid api type: %d, adaptor is nil", apiType), nil } adaptor.Init(meta) modelName := request.Model @@ -84,41 +104,69 @@ func testChannel(channel *model.Channel, request *relaymodel.GeneralOpenAIReques request.Model = modelName convertedRequest, err := adaptor.ConvertRequest(c, relaymode.ChatCompletions, request) if err != nil { - return err, nil + return "", err, nil } jsonData, err := json.Marshal(convertedRequest) if err != nil { - return err, nil + return "", err, nil } + defer func() { + logContent := fmt.Sprintf("渠道 %s 测试成功,响应:%s", channel.Name, responseMessage) + if err != nil || openaiErr != nil { + errorMessage := "" + if err != nil { + errorMessage = err.Error() + } else { + errorMessage = openaiErr.Message + } + logContent = fmt.Sprintf("渠道 %s 测试失败,错误:%s", channel.Name, errorMessage) + } + go model.RecordTestLog(ctx, &model.Log{ + ChannelId: channel.Id, + ModelName: modelName, + Content: logContent, + ElapsedTime: helper.CalcElapsedTime(startTime), + }) + }() logger.SysLog(string(jsonData)) requestBody := bytes.NewBuffer(jsonData) c.Request.Body = io.NopCloser(requestBody) resp, err := adaptor.DoRequest(c, meta, requestBody) if err != nil { - return err, nil + return "", err, nil } if resp != nil && resp.StatusCode != http.StatusOK { err := controller.RelayErrorHandler(resp) - return fmt.Errorf("status code %d: %s", resp.StatusCode, err.Error.Message), &err.Error + errorMessage := err.Error.Message + if errorMessage != "" { + errorMessage = ", error message: " + errorMessage + } + return "", fmt.Errorf("http status code: %d%s", resp.StatusCode, errorMessage), &err.Error } usage, respErr := adaptor.DoResponse(c, resp, meta) if respErr != nil { - return fmt.Errorf("%s", respErr.Error.Message), &respErr.Error + return "", fmt.Errorf("%s", respErr.Error.Message), &respErr.Error } if usage == nil { - return errors.New("usage is nil"), nil + return "", errors.New("usage is nil"), nil + } + rawResponse := w.Body.String() + _, responseMessage, err = parseTestResponse(rawResponse) + if err != nil { + return "", err, nil } result := w.Result() // print result.Body respBody, err := io.ReadAll(result.Body) if err != nil { - return err, nil + return "", err, nil } logger.SysLog(fmt.Sprintf("testing channel #%d, response: \n%s", channel.Id, string(respBody))) - return nil, nil + return responseMessage, nil, nil } func TestChannel(c *gin.Context) { + ctx := c.Request.Context() id, err := strconv.Atoi(c.Param("id")) if err != nil { c.JSON(http.StatusOK, gin.H{ @@ -135,10 +183,10 @@ func TestChannel(c *gin.Context) { }) return } - model := c.Query("model") - testRequest := buildTestRequest(model) + modelName := c.Query("model") + testRequest := buildTestRequest(modelName) tik := time.Now() - err, _ = testChannel(channel, testRequest) + responseMessage, err, _ := testChannel(ctx, channel, testRequest) tok := time.Now() milliseconds := tok.Sub(tik).Milliseconds() if err != nil { @@ -148,18 +196,18 @@ func TestChannel(c *gin.Context) { consumedTime := float64(milliseconds) / 1000.0 if err != nil { c.JSON(http.StatusOK, gin.H{ - "success": false, - "message": err.Error(), - "time": consumedTime, - "model": model, + "success": false, + "message": err.Error(), + "time": consumedTime, + "modelName": modelName, }) return } c.JSON(http.StatusOK, gin.H{ - "success": true, - "message": "", - "time": consumedTime, - "model": model, + "success": true, + "message": responseMessage, + "time": consumedTime, + "modelName": modelName, }) return } @@ -167,7 +215,7 @@ func TestChannel(c *gin.Context) { var testAllChannelsLock sync.Mutex var testAllChannelsRunning bool = false -func testChannels(notify bool, scope string) error { +func testChannels(ctx context.Context, notify bool, scope string) error { if config.RootUserEmail == "" { config.RootUserEmail = model.GetRootUserEmail() } @@ -191,7 +239,7 @@ func testChannels(notify bool, scope string) error { isChannelEnabled := channel.Status == model.ChannelStatusEnabled tik := time.Now() testRequest := buildTestRequest("") - err, openaiErr := testChannel(channel, testRequest) + _, err, openaiErr := testChannel(ctx, channel, testRequest) tok := time.Now() milliseconds := tok.Sub(tik).Milliseconds() if isChannelEnabled && milliseconds > disableThreshold { @@ -225,11 +273,12 @@ func testChannels(notify bool, scope string) error { } func TestChannels(c *gin.Context) { + ctx := c.Request.Context() scope := c.Query("scope") if scope == "" { scope = "all" } - err := testChannels(true, scope) + err := testChannels(ctx, true, scope) if err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, @@ -245,10 +294,11 @@ func TestChannels(c *gin.Context) { } func AutomaticallyTestChannels(frequency int) { + ctx := context.Background() for { time.Sleep(time.Duration(frequency) * time.Minute) logger.SysLog("testing all channels") - _ = testChannels(false, "all") + _ = testChannels(ctx, false, "all") logger.SysLog("channel test finished") } } diff --git a/controller/misc.go b/controller/misc.go index ae900870..75fec8f9 100644 --- a/controller/misc.go +++ b/controller/misc.go @@ -3,13 +3,15 @@ package controller import ( "encoding/json" "fmt" - "github.com/songquanpeng/one-api/common" - "github.com/songquanpeng/one-api/common/config" - "github.com/songquanpeng/one-api/common/message" - "github.com/songquanpeng/one-api/model" "net/http" "strings" + "github.com/songquanpeng/one-api/common" + "github.com/songquanpeng/one-api/common/config" + "github.com/songquanpeng/one-api/common/i18n" + "github.com/songquanpeng/one-api/common/message" + "github.com/songquanpeng/one-api/model" + "github.com/gin-gonic/gin" ) @@ -85,7 +87,7 @@ func SendEmailVerification(c *gin.Context) { if err := common.Validate.Var(email, "required,email"); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": "无效的参数", + "message": i18n.Translate(c, "invalid_parameter"), }) return } @@ -114,10 +116,17 @@ func SendEmailVerification(c *gin.Context) { } code := common.GenerateVerificationCode(6) common.RegisterVerificationCodeWithKey(email, code, common.EmailVerificationPurpose) - subject := fmt.Sprintf("%s邮箱验证邮件", config.SystemName) - content := fmt.Sprintf("

您好,你正在进行%s邮箱验证。

"+ - "

您的验证码为: %s

"+ - "

验证码 %d 分钟内有效,如果不是本人操作,请忽略。

", config.SystemName, code, common.VerificationValidMinutes) + subject := fmt.Sprintf("%s 邮箱验证邮件", config.SystemName) + content := message.EmailTemplate( + subject, + fmt.Sprintf(` +

您好!

+

您正在进行 %s 邮箱验证。

+

您的验证码为:

+

%s

+

验证码 %d 分钟内有效,如果不是本人操作,请忽略。

+ `, config.SystemName, code, common.VerificationValidMinutes), + ) err := message.SendEmail(subject, email, content) if err != nil { c.JSON(http.StatusOK, gin.H{ @@ -138,7 +147,7 @@ func SendPasswordResetEmail(c *gin.Context) { if err := common.Validate.Var(email, "required,email"); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": "无效的参数", + "message": i18n.Translate(c, "invalid_parameter"), }) return } @@ -152,16 +161,26 @@ func SendPasswordResetEmail(c *gin.Context) { code := common.GenerateVerificationCode(0) common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose) link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", config.ServerAddress, email, code) - subject := fmt.Sprintf("%s密码重置", config.SystemName) - content := fmt.Sprintf("

您好,你正在进行%s密码重置。

"+ - "

点击 此处 进行密码重置。

"+ - "

如果链接无法点击,请尝试点击下面的链接或将其复制到浏览器中打开:
%s

"+ - "

重置链接 %d 分钟内有效,如果不是本人操作,请忽略。

", config.SystemName, link, link, common.VerificationValidMinutes) + subject := fmt.Sprintf("%s 密码重置", config.SystemName) + content := message.EmailTemplate( + subject, + fmt.Sprintf(` +

您好!

+

您正在进行 %s 密码重置。

+

请点击下面的按钮进行密码重置:

+

+ 重置密码 +

+

如果按钮无法点击,请复制以下链接到浏览器中打开:

+

%s

+

重置链接 %d 分钟内有效,如果不是本人操作,请忽略。

+ `, config.SystemName, link, link, common.VerificationValidMinutes), + ) err := message.SendEmail(subject, email, content) if err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": err.Error(), + "message": fmt.Sprintf("%s%s", i18n.Translate(c, "send_email_failed"), err.Error()), }) return } @@ -183,7 +202,7 @@ func ResetPassword(c *gin.Context) { if req.Email == "" || req.Token == "" { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": "无效的参数", + "message": i18n.Translate(c, "invalid_parameter"), }) return } diff --git a/controller/option.go b/controller/option.go index f86e3a64..310086ef 100644 --- a/controller/option.go +++ b/controller/option.go @@ -2,12 +2,14 @@ package controller import ( "encoding/json" - "github.com/songquanpeng/one-api/common/config" - "github.com/songquanpeng/one-api/common/helper" - "github.com/songquanpeng/one-api/model" "net/http" "strings" + "github.com/songquanpeng/one-api/common/config" + "github.com/songquanpeng/one-api/common/helper" + "github.com/songquanpeng/one-api/common/i18n" + "github.com/songquanpeng/one-api/model" + "github.com/gin-gonic/gin" ) @@ -38,7 +40,7 @@ func UpdateOption(c *gin.Context) { if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "success": false, - "message": "无效的参数", + "message": i18n.Translate(c, "invalid_parameter"), }) return } diff --git a/controller/user.go b/controller/user.go index e79881c2..d7fd8d77 100644 --- a/controller/user.go +++ b/controller/user.go @@ -3,17 +3,19 @@ package controller import ( "encoding/json" "fmt" - "github.com/songquanpeng/one-api/common" - "github.com/songquanpeng/one-api/common/config" - "github.com/songquanpeng/one-api/common/ctxkey" - "github.com/songquanpeng/one-api/common/random" - "github.com/songquanpeng/one-api/model" "net/http" "strconv" "time" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" + + "github.com/songquanpeng/one-api/common" + "github.com/songquanpeng/one-api/common/config" + "github.com/songquanpeng/one-api/common/ctxkey" + "github.com/songquanpeng/one-api/common/i18n" + "github.com/songquanpeng/one-api/common/random" + "github.com/songquanpeng/one-api/model" ) type LoginRequest struct { @@ -33,7 +35,7 @@ func Login(c *gin.Context) { err := json.NewDecoder(c.Request.Body).Decode(&loginRequest) if err != nil { c.JSON(http.StatusOK, gin.H{ - "message": "无效的参数", + "message": i18n.Translate(c, "invalid_parameter"), "success": false, }) return @@ -42,7 +44,7 @@ func Login(c *gin.Context) { password := loginRequest.Password if username == "" || password == "" { c.JSON(http.StatusOK, gin.H{ - "message": "无效的参数", + "message": i18n.Translate(c, "invalid_parameter"), "success": false, }) return @@ -109,6 +111,7 @@ func Logout(c *gin.Context) { } func Register(c *gin.Context) { + ctx := c.Request.Context() if !config.RegisterEnabled { c.JSON(http.StatusOK, gin.H{ "message": "管理员关闭了新用户注册", @@ -128,14 +131,14 @@ func Register(c *gin.Context) { if err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": "无效的参数", + "message": i18n.Translate(c, "invalid_parameter"), }) return } if err := common.Validate.Struct(&user); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": "输入不合法 " + err.Error(), + "message": i18n.Translate(c, "invalid_input"), }) return } @@ -166,7 +169,7 @@ func Register(c *gin.Context) { if config.EmailVerificationEnabled { cleanUser.Email = user.Email } - if err := cleanUser.Insert(inviterId); err != nil { + if err := cleanUser.Insert(ctx, inviterId); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, "message": err.Error(), @@ -362,12 +365,13 @@ func GetSelf(c *gin.Context) { } func UpdateUser(c *gin.Context) { + ctx := c.Request.Context() var updatedUser model.User err := json.NewDecoder(c.Request.Body).Decode(&updatedUser) if err != nil || updatedUser.Id == 0 { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": "无效的参数", + "message": i18n.Translate(c, "invalid_parameter"), }) return } @@ -377,7 +381,7 @@ func UpdateUser(c *gin.Context) { if err := common.Validate.Struct(&updatedUser); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": "输入不合法 " + err.Error(), + "message": i18n.Translate(c, "invalid_input"), }) return } @@ -416,7 +420,7 @@ func UpdateUser(c *gin.Context) { return } if originUser.Quota != updatedUser.Quota { - model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", common.LogQuota(originUser.Quota), common.LogQuota(updatedUser.Quota))) + model.RecordLog(ctx, originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", common.LogQuota(originUser.Quota), common.LogQuota(updatedUser.Quota))) } c.JSON(http.StatusOK, gin.H{ "success": true, @@ -431,7 +435,7 @@ func UpdateSelf(c *gin.Context) { if err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": "无效的参数", + "message": i18n.Translate(c, "invalid_parameter"), }) return } @@ -535,19 +539,20 @@ func DeleteSelf(c *gin.Context) { } func CreateUser(c *gin.Context) { + ctx := c.Request.Context() var user model.User err := json.NewDecoder(c.Request.Body).Decode(&user) if err != nil || user.Username == "" || user.Password == "" { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": "无效的参数", + "message": i18n.Translate(c, "invalid_parameter"), }) return } if err := common.Validate.Struct(&user); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": "输入不合法 " + err.Error(), + "message": i18n.Translate(c, "invalid_input"), }) return } @@ -568,7 +573,7 @@ func CreateUser(c *gin.Context) { Password: user.Password, DisplayName: user.DisplayName, } - if err := cleanUser.Insert(0); err != nil { + if err := cleanUser.Insert(ctx, 0); err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, "message": err.Error(), @@ -596,7 +601,7 @@ func ManageUser(c *gin.Context) { if err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, - "message": "无效的参数", + "message": i18n.Translate(c, "invalid_parameter"), }) return } @@ -747,6 +752,7 @@ type topUpRequest struct { } func TopUp(c *gin.Context) { + ctx := c.Request.Context() req := topUpRequest{} err := c.ShouldBindJSON(&req) if err != nil { @@ -757,7 +763,7 @@ func TopUp(c *gin.Context) { return } id := c.GetInt("id") - quota, err := model.Redeem(req.Key, id) + quota, err := model.Redeem(ctx, req.Key, id) if err != nil { c.JSON(http.StatusOK, gin.H{ "success": false, @@ -780,6 +786,7 @@ type adminTopUpRequest struct { } func AdminTopUp(c *gin.Context) { + ctx := c.Request.Context() req := adminTopUpRequest{} err := c.ShouldBindJSON(&req) if err != nil { @@ -800,7 +807,7 @@ func AdminTopUp(c *gin.Context) { if req.Remark == "" { req.Remark = fmt.Sprintf("通过 API 充值 %s", common.LogQuota(int64(req.Quota))) } - model.RecordTopupLog(req.UserId, req.Remark, req.Quota) + model.RecordTopupLog(ctx, req.UserId, req.Remark, req.Quota) c.JSON(http.StatusOK, gin.H{ "success": true, "message": "", diff --git a/go.mod b/go.mod index 2106cf0f..b726ed44 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,5 @@ module github.com/songquanpeng/one-api -// +heroku goVersion go1.18 go 1.20 require ( @@ -27,10 +26,11 @@ require ( github.com/stretchr/testify v1.9.0 golang.org/x/crypto v0.31.0 golang.org/x/image v0.18.0 + golang.org/x/sync v0.10.0 google.golang.org/api v0.187.0 gorm.io/driver/mysql v1.5.6 gorm.io/driver/postgres v1.5.7 - gorm.io/driver/sqlite v1.5.5 + gorm.io/driver/sqlite v1.5.1 gorm.io/gorm v1.25.10 ) @@ -82,7 +82,7 @@ require ( github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect - github.com/mattn/go-sqlite3 v1.14.22 // indirect + github.com/mattn/go-sqlite3 v1.14.24 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect @@ -99,7 +99,6 @@ require ( golang.org/x/arch v0.8.0 // indirect golang.org/x/net v0.26.0 // indirect golang.org/x/oauth2 v0.21.0 // indirect - golang.org/x/sync v0.10.0 // indirect golang.org/x/sys v0.28.0 // indirect golang.org/x/text v0.21.0 // indirect golang.org/x/time v0.5.0 // indirect diff --git a/go.sum b/go.sum index c98f1965..39541369 100644 --- a/go.sum +++ b/go.sum @@ -163,8 +163,8 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= -github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM= +github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -306,8 +306,8 @@ gorm.io/driver/mysql v1.5.6 h1:Ld4mkIickM+EliaQZQx3uOJDJHtrd70MxAUqWqlx3Y8= gorm.io/driver/mysql v1.5.6/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= gorm.io/driver/postgres v1.5.7 h1:8ptbNJTDbEmhdr62uReG5BGkdQyeasu/FZHxI0IMGnM= gorm.io/driver/postgres v1.5.7/go.mod h1:3e019WlBaYI5o5LIdNV+LyxCMNtLOQETBXL2h4chKpA= -gorm.io/driver/sqlite v1.5.5 h1:7MDMtUZhV065SilG62E0MquljeArQZNfJnjd9i9gx3E= -gorm.io/driver/sqlite v1.5.5/go.mod h1:6NgQ7sQWAIFsPrJJl1lSNSu2TABh0ZZ/zm5fosATavE= +gorm.io/driver/sqlite v1.5.1 h1:hYyrLkAWE71bcarJDPdZNTLWtr8XrSjOWyjUYI6xdL4= +gorm.io/driver/sqlite v1.5.1/go.mod h1:7MZZ2Z8bqyfSQA1gYEV6MagQWj3cpUkJj9Z+d1HEMEQ= gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s= gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= diff --git a/i18n/en.json b/i18n/en.json deleted file mode 100644 index b7f1bd3e..00000000 --- a/i18n/en.json +++ /dev/null @@ -1,778 +0,0 @@ -{ - "$%.6f 额度": "$%.6f quota", - "%d 点额度": "%d point quota", - "尚未实现": "Not yet implemented", - "余额不足": "Insufficient balance", - "危险操作": "Hazardous operations", - "输入你的账户名": "Enter your account name", - "确认删除": "Confirm Delete", - "确认绑定": "Confirm Binding", - "您正在删除自己的帐户,将清空所有数据且不可恢复": "You are deleting your account, all data will be cleared and unrecoverable.", - "\"渠道「%s」(#%d)已被禁用\"": "\"Channel %s (#%d) has been disabled\"", - "渠道「%s」(#%d)已被禁用,原因:%s": "Channel %s (#%d) has been disabled, reason: %s", - "测试已在运行中": "Test is already running", - "响应时间 %.2fs 超过阈值 %.2fs": "Response time %.2fs exceeds threshold %.2fs", - "渠道测试完成": "Channel test completed", - "渠道测试完成,如果没有收到禁用通知,说明所有渠道都正常": "Channel test completed, if you have not received the disable notification, it means that all channels are normal", - "无法连接至 GitHub 服务器,请稍后重试!": "Unable to connect to GitHub server, please try again later!", - "返回值非法,用户字段为空,请稍后重试!": "The return value is illegal, the user field is empty, please try again later!", - "管理员未开启通过 GitHub 登录以及注册": "The administrator did not turn on login and registration via GitHub", - "管理员关闭了新用户注册": "The administrator has turned off new user registration", - "用户已被封禁": "User has been banned", - "该 GitHub 账户已被绑定": "The GitHub account has been bound", - "邮箱地址已被占用": "Email address is occupied", - "%s邮箱验证邮件": "%s Email verification email", - "

您好,你正在进行%s邮箱验证。

": "

Hello, you are verifying %s email.

", - "

您的验证码为: %s

": "

Your verification code is: %s

", - "

验证码 %d 分钟内有效,如果不是本人操作,请忽略。

": "

The verification code is valid within %d minutes. If it is not your operation, please ignore it.

", - "无效的参数": "Invalid parameter", - "该邮箱地址未注册": "The email address is not registered", - "%s密码重置": "%s Password reset", - "

您好,你正在进行%s密码重置。

": "

Hello, you are resetting %s password.

", - "

点击此处进行密码重置。

": "

Click here to reset your password.

", - "

重置链接 %d 分钟内有效,如果不是本人操作,请忽略。

": "

The reset link is valid within %d minutes. If it is not your operation, please ignore it.

", - "重置链接非法或已过期": "Reset link is illegal or expired", - "无法启用 GitHub OAuth,请先填入 GitHub Client ID 以及 GitHub Client Secret!": "Unable to enable GitHub OAuth, please fill in GitHub Client ID and GitHub Client Secret first!", - "无法启用微信登录,请先填入微信登录相关配置信息!": "Unable to enable WeChat login, please fill in the relevant configuration information for WeChat login first!", - "无法启用 Turnstile 校验,请先填入 Turnstile 校验相关配置信息!": "Unable to enable Turnstile verification, please fill in the relevant configuration information for Turnstile verification first!", - "兑换码名称长度必须在1-20之间": "The length of the redemption code name must be between 1-20", - "兑换码个数必须大于0": "The number of redemption codes must be greater than 0", - "一次兑换码批量生成的个数不能大于 100": "The number of redemption codes generated in a batch cannot be greater than 100", - "通过令牌「%s」使用模型 %s 消耗 %s(模型倍率 %.2f,分组倍率 %.2f)": "Using model %s with token %s consumes %s (model rate %.2f, group rate %.2f)", - "当前分组上游负载已饱和,请稍后再试": "The current group load is saturated, please try again later", - "令牌名称过长": "Token name is too long", - "令牌已过期,无法启用,请先修改令牌过期时间,或者设置为永不过期": "The token has expired and cannot be enabled. Please modify the expiration time of the token, or set it to never expire.", - "令牌可用额度已用尽,无法启用,请先修改令牌剩余额度,或者设置为无限额度": "The available quota of the token has been used up and cannot be enabled. Please modify the remaining quota of the token, or set it to unlimited quota", - "管理员关闭了密码登录": "The administrator has turned off password login", - "无法保存会话信息,请重试": "Unable to save session information, please try again", - "管理员关闭了通过密码进行注册,请使用第三方账户验证的形式进行注册": "The administrator has turned off registration via password. Please use the form of third-party account verification to register", - "输入不合法 ": "Input is illegal ", - "管理员开启了邮箱验证,请输入邮箱地址和验证码": "The administrator has turned on email verification, please enter the email address and verification code", - "验证码错误或已过期": "Verification code error or expired", - "无权获取同级或更高等级用户的信息": "No permission to get information of users at the same level or higher", - "请重试,系统生成的 UUID 竟然重复了!": "Please try again, the system-generated UUID is actually duplicated!", - "输入不合法": "Input is illegal", - "无权更新同权限等级或更高权限等级的用户信息": "No permission to update user information with the same permission level or higher permission level", - "管理员将用户额度从 %s修改为 %s": "The administrator changed the user quota from %s to %s", - "无权删除同权限等级或更高权限等级的用户": "No permission to delete users with the same permission level or higher permission level", - "无法创建权限大于等于自己的用户": "Unable to create users with permissions greater than or equal to your own", - "用户不存在": "User does not exist", - "无法禁用超级管理员用户": "Unable to disable super administrator user", - "无法删除超级管理员用户": "Unable to delete super administrator user", - "普通管理员用户无法提升其他用户为管理员": "Ordinary administrator users cannot promote other users to administrators", - "该用户已经是管理员": "The user is already an administrator", - "无法降级超级管理员用户": "Unable to downgrade super administrator user", - "该用户已经是普通用户": "The user is already an ordinary user", - "管理员未开启通过微信登录以及注册": "The administrator has not enabled login and registration via WeChat", - "该微信账号已被绑定": "The WeChat account has been bound", - "无权进行此操作,未登录且未提供 access token": "No permission to perform this operation, not logged in and no access token provided", - "无权进行此操作,access token 无效": "No permission to perform this operation, access token is invalid", - "无权进行此操作,权限不足": "No permission to perform this operation, insufficient permissions", - "普通用户不支持指定渠道": "Ordinary users do not support specifying channels", - "无效的渠道 ID": "Invalid channel ID", - "该渠道已被禁用": "The channel has been disabled", - "无效的请求": "Invalid request", - "无可用渠道": "No available channels", - "Turnstile token 为空": "Turnstile token is empty", - "Turnstile 校验失败,请刷新重试!": "Turnstile verification failed, please refresh and try again!", - "id 为空!": "id is empty!", - "未提供兑换码": "No redemption code provided", - "无效的 user id": "Invalid user id", - "无效的兑换码": "Invalid redemption code", - "该兑换码已被使用": "The redemption code has been used", - "通过兑换码充值 %s": "Recharge %s through redemption code", - "未提供令牌": "No token provided", - "该令牌状态不可用": "The token status is not available", - "该令牌已过期": "The token has expired", - "该令牌额度已用尽": "The token quota has been used up", - "无效的令牌": "Invalid token", - "令牌验证失败": "Token verification failed", - "id 或 userId 为空!": "id or userId is empty!", - "quota 不能为负数!": "quota cannot be negative!", - "令牌额度不足": "Insufficient token quota", - "用户额度不足": "Insufficient user quota", - "您的额度即将用尽": "Your quota is about to run out", - "您的额度已用尽": "Your quota has been used up", - "%s,当前剩余额度为 %d,为了不影响您的使用,请及时充值。
充值链接:%s": "%s, the current remaining quota is %d, in order not to affect your use, please recharge in time.
Recharge link: %s", - "affCode 为空!": "affCode is empty!", - "新用户注册赠送 %s": "New user registration gives %s", - "使用邀请码赠送 %s": "Use invitation code to give %s", - "邀请用户赠送 %s": "Invite users to give %s", - "用户名或密码为空": "Username or password is empty", - "用户名或密码错误,或用户已被封禁": "Username or password is wrong, or user has been banned", - "email 为空!": "email is empty!", - "GitHub id 为空!": "GitHub id is empty!", - "WeChat id 为空!": "WeChat id is empty!", - "username 为空!": "username is empty!", - "邮箱地址或密码为空!": "Email address or password is empty!", - "OpenAI 接口聚合管理,支持多种渠道包括 Azure,可用于二次分发管理 key,仅单可执行文件,已打包好 Docker 镜像,一键部署,开箱即用": "OpenAI interface aggregation management, supports multiple channels including Azure, can be used for secondary distribution management key, only single executable file, Docker image has been packaged, one-click deployment, out of the box", - "未知类型": "Unknown type", - "不支持": "Not supported", - "操作成功完成!": "Operation completed successfully!", - "已启用": "Enabled", - "已禁用": "Disabled", - "未知状态": "Unknown status", - " 秒": "s", - " 分钟 ": " m ", - " 小时 ": " h ", - " 天 ": " d ", - " 个月 ": " M ", - " 年 ": " y ", - "未测试": "Not tested", - "渠道 ${name} 测试成功,耗时 ${time.toFixed(2)} 秒。": "Channel ${name} test succeeded, time consumed ${time.toFixed(2)} s.", - "已成功开始测试所有渠道,请刷新页面查看结果。": "All channels have been successfully tested, please refresh the page to view the results.", - "已成功开始测试所有已启用渠道,请刷新页面查看结果。": "All enabled channels have been successfully tested, please refresh the page to view the results.", - "渠道 ${name} 余额更新成功!": "Channel ${name} balance updated successfully!", - "已更新完毕所有已启用渠道余额!": "The balance of all enabled channels has been updated!", - "搜索渠道的 ID,名称和密钥 ...": "Search for channel ID, name and key ...", - "名称": "Name", - "分组": "Group", - "类型": "Type", - "状态": "Status", - "响应时间": "Response time", - "余额": "Balance", - "操作": "Operation", - "未更新": "Not updated", - "测试": "Test", - "更新余额": "Update balance", - "删除": "Delete", - "删除渠道 {channel.name}": "Delete channel {channel.name}", - "禁用": "Disable", - "启用": "Enable", - "编辑": "Edit", - "添加新的渠道": "Add a new channel", - "测试所有渠道": "Test all channels", - "测试所有已启用渠道": "Test all enabled channels", - "更新所有已启用渠道余额": "Update the balance of all enabled channels", - "刷新": "Refresh", - "处理中...": "Processing...", - "绑定成功!": "Binding succeeded!", - "登录成功!": "Login succeeded!", - "操作失败,重定向至登录界面中...": "Operation failed, redirecting to the login page...", - "出现错误,第 ${count} 次重试中...": "An error occurred, retrying for the ${count} time...", - "首页": "Home", - "渠道": "Channel", - "令牌": "Token", - "兑换": "Redeem", - "充值": "Recharge", - "用户": "User", - "日志": "Log", - "设置": "Settings", - "关于": "About", - "聊天": "Chat", - "注销成功!": "Logout succeeded!", - "注销": "Logout", - "登录": "Login", - "注册": "Register", - "加载{name}中...": "Loading {name}...", - "未登录或登录已过期,请重新登录!": "Not logged in or login has expired, please log in again!", - "用户登录": "User login", - "\"用户名\"": "\"Username\"", - "\"密码\"": "\"Password\"", - "忘记密码?": "Forget password?", - "点击重置": "Click to reset", - "; 没有账户?": "; No account?", - "点击注册": "Click to register", - "微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)": "Scan the QR code of WeChat to follow the official account, enter \"verification code\" to get the verification code (valid within three minutes)", - "\"验证码\"": "\"Verification code\"", - "全部用户": "All users", - "当前用户": "Current user", - "'全部'": "'All'", - "'充值'": "'Recharge'", - "'消费'": "'Consumption'", - "'管理'": "'Management'", - "'系统'": "'System'", - " 充值 ": " Recharge ", - " 消费 ": " Consumption ", - " 管理 ": " Management ", - " 系统 ": " System ", - " 未知 ": " Unknown ", - "时间": "Time", - "详情": "Details", - "选择模式": "Select mode", - "选择明细分类": "Select details category", - "模型倍率不是合法的 JSON 字符串": "Model rate is not a valid JSON string", - "分组倍率不是合法的 JSON 字符串": "Group rate is not a valid JSON string", - "通用设置": "General Settings", - "充值链接": "Recharge Link", - "例如发卡网站的购买链接": "For example, the purchase link of the card issuing website", - "聊天页面链接": "Chat Page Link", - "例如 ChatGPT Next Web 的部署地址": "For example, the deployment address of ChatGPT Next Web", - "单位美元额度": "Unit Dollar Quota", - "一单位货币能兑换的额度": "Quota that can be exchanged for one unit of currency", - "启用额度消费日志记录": "Enable quota consumption log recording", - "以货币形式显示额度": "Display quota in the form of currency", - "相关 API 显示令牌额度而非用户额度": "Related API displays token quota instead of user quota", - "保存通用设置": "Save General Settings", - "监控设置": "Monitoring Settings", - "最长响应时间": "Longest Response Time", - "单位秒": "Unit in seconds", - "当运行渠道全部测试时": "When all operating channels are tested", - "超过此时间将自动禁用渠道": "Channels will be automatically disabled if this time is exceeded", - "额度提醒阈值": "Quota reminder threshold", - "低于此额度时将发送邮件提醒用户": "Email will be sent to remind users when the quota is below this", - "失败时自动禁用渠道": "Automatically disable the channel when it fails", - "保存监控设置": "Save Monitoring Settings", - "额度设置": "Quota Settings", - "新用户初始额度": "Initial quota for new users", - "例如": "For example", - "请求预扣费额度": "Request for pre-deducted quota", - "请求结束后多退少补": "Refund more or less after the request ends", - "邀请新用户奖励额度": "Invite new users to reward quota", - "新用户使用邀请码奖励额度": "New user rewards quota using invitation code", - "保存额度设置": "Save Quota Settings", - "倍率设置": "Rate Settings", - "模型倍率": "Model rate", - "为一个 JSON 文本": "Is a JSON text", - "键为模型名称": "Key is model name", - "值为倍率": "Value is the rate", - "分组倍率": "Group rate", - "键为分组名称": "Key is group name", - "保存倍率设置": "Save Rate Settings", - "已是最新版本": "Is the latest version", - "检查更新": "Check for updates", - "公告": "Announcement", - "在此输入新的公告内容,支持 Markdown & HTML 代码": "Enter the new announcement content here, supports Markdown & HTML code", - "保存公告": "Save Announcement", - "个性化设置": "Personalization Settings", - "系统名称": "System Name", - "在此输入系统名称": "Enter the system name here", - "设置系统名称": "Set system name", - "图片地址": "Image URL", - "在此输入 Logo 图片地址": "Enter the Logo image URL here", - "首页内容": "Home Page Content", - "在此输入首页内容,支持 Markdown & HTML 代码,设置后首页的状态信息将不再显示。如果输入的是一个链接,则会使用该链接作为 iframe 的 src 属性,这允许你设置任意网页作为首页": "Enter the homepage content here, supports Markdown & HTML code. Once set, the status information of the homepage will not be displayed. If a link is entered, it will be used as the src attribute of the iframe, allowing you to set any webpage as the homepage.", - "保存首页内容": "Save Home Page Content", - "在此输入新的关于内容,支持 Markdown & HTML 代码。如果输入的是一个链接,则会使用该链接作为 iframe 的 src 属性,这允许你设置任意网页作为关于页面": "Enter new about content here, supports Markdown & HTML code. If a link is entered, it will be used as the src attribute of the iframe, allowing you to set any webpage as the about page.", - "保存关于": "Save About", - "移除 One API 的版权标识必须首先获得授权,项目维护需要花费大量精力,如果本项目对你有意义,请主动支持本项目": "Removal of One API copyright mark must first be authorized. Project maintenance requires a lot of effort. If this project is meaningful to you, please actively support it.", - "页脚": "Footer", - "在此输入新的页脚,留空则使用默认页脚,支持 HTML 代码": "Enter the new footer here, leave blank to use the default footer, supports HTML code.", - "设置页脚": "Set Footer", - "新版本": "New Version", - "关闭": "Close", - "密码已重置并已复制到剪贴板": "Password has been reset and copied to clipboard", - "密码重置确认": "Password Reset Confirmation", - "邮箱地址": "Email Address", - "提交": "Submit", - "请稍后几秒重试": "Please retry in a few seconds", - "正在检查用户环境": "Checking user environment", - "重置邮件发送成功": "Reset mail sent successfully", - "请检查邮箱": "Please check your email", - "密码重置": "Password Reset", - "令牌已重置并已复制到剪贴板": "Token has been reset and copied to clipboard", - "邀请链接已复制到剪切板": "Invitation link has been copied to clipboard", - "微信账户绑定成功": "WeChat account binding succeeded", - "验证码发送成功": "Verification code sent successfully", - "邮箱账户绑定成功": "Email account binding succeeded", - "注意": "Note", - "此处生成的令牌用于系统管理": "The token generated here is used for system management", - "而非用于请求 OpenAI 相关的服务": "Not for requesting OpenAI related services", - "请知悉": "Please be aware", - "更新个人信息": "Update Personal Information", - "生成系统访问令牌": "Generate System Access Token", - "复制邀请链接": "Copy Invitation Link", - "账号绑定": "Account Binding", - "绑定微信账号": "Bind WeChat Account", - "微信扫码关注公众号": "Scan the QR code with WeChat to follow the official account", - "输入": "Enter", - "验证码": "Verification Code", - "获取验证码": "Get Verification Code", - "三分钟内有效": "Valid for three minutes", - "绑定": "Bind", - "绑定 GitHub 账号": "Bind GitHub Account", - "绑定邮箱地址": "Bind Email Address", - "输入邮箱地址": "Enter Email Address", - "未使用": "Unused", - "已使用": "Used", - "操作成功完成": "Operation successfully completed", - "搜索兑换码的 ID 和名称": "Search for ID and name", - "额度": "Quota", - "创建时间": "Creation Time", - "兑换时间": "Redemption Time", - "尚未兑换": "Not yet redeemed", - "已复制到剪贴板": "Copied to clipboard", - "无法复制到剪贴板": "Unable to copy to clipboard", - "请手动复制": "Please copy manually", - "已将兑换码填入搜索框": "The voucher code has been filled into the search box", - "复制": "Copy", - "添加新的兑换码": "Add a new voucher", - "密码长度不得小于 8 位": "Password length must not be less than 8 characters", - "两次输入的密码不一致": "The two passwords entered do not match", - "注册成功": "Registration succeeded", - "请稍后几秒重试,Turnstile 正在检查用户环境": "Please retry in a few seconds, Turnstile is checking user environment", - "验证码发送成功,请检查你的邮箱": "Verification code sent successfully, please check your email", - "新用户注册": "New User Registration", - "输入用户名,最长 12 位": "Enter username, up to 12 characters", - "输入密码,最短 8 位,最长 20 位": "Enter password, at least 8 characters and up to 20 characters", - "输入验证码": "Enter Verification Code", - "已有账户": "Already have an account", - "点击登录": "Click to log in", - "服务器地址": "Server Address", - "更新服务器地址": "Update Server Address", - "配置登录注册": "Configure Login/Registration", - "允许通过密码进行登录": "Allow login via password", - "允许通过密码进行注册": "Allow registration via password", - "通过密码注册时需要进行邮箱验证": "Email verification is required when registering via password", - "允许通过 GitHub 账户登录 & 注册": "Allow login & registration via GitHub account", - "允许通过微信登录 & 注册": "Allow login & registration via WeChat", - "允许新用户注册(此项为否时,新用户将无法以任何方式进行注册": "Allow new user registration (if this option is off, new users will not be able to register in any way", - "启用 Turnstile 用户校验": "Enable Turnstile user verification", - "配置 SMTP": "Configure SMTP", - "用以支持系统的邮件发送": "To support the system email sending", - "SMTP 服务器地址": "SMTP Server Address", - "例如:smtp.qq.com": "For example: smtp.qq.com", - "SMTP 端口": "SMTP Port", - "默认: 587": "Default: 587", - "SMTP 账户": "SMTP Account", - "通常是邮箱地址": "Usually an email address", - "发送者邮箱": "Sender email", - "通常和邮箱地址保持一致": "Usually consistent with the email address", - "SMTP 访问凭证": "SMTP Access Credential", - "敏感信息不会发送到前端显示": "Sensitive information will not be displayed in the frontend", - "保存 SMTP 设置": "Save SMTP Settings", - "配置 GitHub OAuth App": "Configure GitHub OAuth App", - "用以支持通过 GitHub 进行登录注册": "To support login & registration via GitHub", - "点击此处": "Click here", - "管理你的 GitHub OAuth App": "Manage your GitHub OAuth App", - "输入你注册的 GitHub OAuth APP 的 ID": "Enter your registered GitHub OAuth APP ID", - "保存 GitHub OAuth 设置": "Save GitHub OAuth Settings", - "配置 WeChat Server": "Configure WeChat Server", - "用以支持通过微信进行登录注册": "To support login & registration via WeChat", - "了解 WeChat Server": "Learn about WeChat Server", - "WeChat Server 访问凭证": "WeChat Server Access Credential", - "微信公众号二维码图片链接": "WeChat Public Account QR Code Image Link", - "输入一个图片链接": "Enter an image link", - "保存 WeChat Server 设置": "Save WeChat Server Settings", - "配置 Turnstile": "Configure Turnstile", - "用以支持用户校验": "To support user verification", - "管理你的 Turnstile Sites,推荐选择 Invisible Widget Type": "Manage your Turnstile Sites, recommend selecting Invisible Widget Type", - "输入你注册的 Turnstile Site Key": "Enter your registered Turnstile Site Key", - "保存 Turnstile 设置": "Save Turnstile Settings", - "已过期": "Expired", - "已耗尽": "Exhausted", - "搜索令牌的名称 ...": "Search for the name of the token...", - "已用额度": "Quota used", - "剩余额度": "Remaining quota", - "过期时间": "Expiration time", - "无": "None", - "无限制": "Unlimited", - "永不过期": "Never expires", - "无法复制到剪贴板,请手动复制,已将令牌填入搜索框": "Unable to copy to clipboard, please copy manually, the token has been entered into the search box", - "删除令牌": "Delete Token", - "添加新的令牌": "Add New Token", - "普通用户": "Regular User", - "管理员": "Admin", - "超级管理员": "Super Admin", - "未知身份": "Unknown Identity", - "已激活": "Activated", - "已封禁": "Banned", - "搜索用户的 ID,用户名,显示名称,以及邮箱地址 ...": "Search user ID, username, display name, and email address...", - "用户名": "Username", - "统计信息": "Statistics", - "用户角色": "User Role", - "未绑定邮箱地址": "Email not bound", - "请求次数": "Number of Requests", - "提升": "Promote", - "降级": "Demote", - "删除用户": "Delete User", - "添加新的用户": "Add New User", - "自定义": "Custom", - "等价金额": "Equivalent Amount", - "未登录或登录已过期,请重新登录": "Not logged in or login has expired, please log in again", - "请求次数过多,请稍后再试": "Too many requests, please try again later", - "服务器内部错误,请联系管理员": "Server internal error, please contact the administrator", - "本站仅作演示之用,无服务端": "This site is for demonstration purposes only, no server-side", - "超级管理员未设置充值链接!": "Super administrator has not set the recharge link!", - "错误:": "Error: ", - "新版本可用:${data.version},请使用快捷键 Shift + F5 刷新页面": "New version available: ${data.version}, please refresh the page using shortcut Shift + F5", - "无法正常连接至服务器": "Unable to connect to the server normally", - "管理渠道": "Manage Channels", - "系统状况": "System Status", - "系统信息": "System Information", - "系统信息总览": "System Information Overview", - "版本": "Version", - "源码": "Source Code", - "启动时间": "Startup Time", - "系统配置": "System Configuration", - "系统配置总览": "System Configuration Overview", - "邮箱验证": "Email Verification", - "未启用": "Not Enabled", - "GitHub 身份验证": "GitHub Authentication", - "微信身份验证": "WeChat Authentication", - "Turnstile 用户校验": "Turnstile User Verification", - "创建新的渠道": "Create New Channel", - "镜像": "Mirror", - "请输入镜像站地址,格式为:https://domain.com,可不填,不填则使用渠道默认值": "Please enter the mirror site address, the format is: https://domain.com, it can be left blank, if left blank, the default value of the channel will be used", - "模型": "Model", - "请选择该渠道所支持的模型": "Please select the model supported by the channel", - "填入基础模型": "Fill in the basic model", - "填入所有模型": "Fill in all models", - "清除所有模型": "Clear all models", - "密钥": "Key", - "请输入密钥": "Please enter the key", - "批量创建": "Batch Create", - "更新渠道信息": "Update Channel Information", - "我的令牌": "My Tokens", - "管理兑换码": "Manage Redeem Codes", - "兑换码": "Redeem Code", - "管理用户": "Manage Users", - "额度明细": "Quota Details", - "个人设置": "Personal Settings", - "运营设置": "Operation Settings", - "系统设置": "System Settings", - "其他设置": "Other Settings", - "项目仓库地址": "Project Repository Address", - "可在设置页面设置关于内容,支持 HTML & Markdown": "You can set the content about in the settings page, support HTML & Markdown", - "由{' '}": "built by{' '}", - "构建,源代码遵循{' '}": ", the source code licensed under{' '}", - "MIT 协议": "MIT License", - "充值额度": "Recharge Quota", - "获取兑换码": "Get Redeem Code", - "一个月后过期": "Expires after one month", - "一天后过期": "Expires after one day", - "一小时后过期": "Expires after one hour", - "一分钟后过期": "Expires after one minute", - "创建新的令牌": "Create New Token", - "注意,令牌的额度仅用于限制令牌本身的最大额度使用量,实际的使用受到账户的剩余额度限制。": "Note that the quota of the token is only used to limit the maximum quota usage of the token itself, and the actual usage is limited by the remaining quota of the account.", - "设为无限额度": "Set to unlimited quota", - "更新令牌信息": "Update Token Information", - "请输入充值码!": "Please enter the recharge code!", - "请输入名称": "Please enter a name", - "请输入密钥,一行一个": "Please enter the key, one per line", - "请输入额度": "Please enter the quota", - "令牌创建成功": "Token created successfully", - "令牌更新成功": "Token updated successfully", - "充值成功!": "Recharge successful!", - "更新用户信息": "Update User Information", - "请输入新的用户名": "Please enter a new username", - "密码": "Password", - "请输入新的密码": "Please enter a new password", - "显示名称": "Display Name", - "请输入新的显示名称": "Please enter a new display name", - "已绑定的 GitHub 账户": "GitHub Account Bound", - "此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改": "This item is read-only. Users need to bind through the relevant binding button on the personal settings page, and cannot be modified directly", - "已绑定的微信账户": "WeChat Account Bound", - "已绑定的邮箱账户": "Email Account Bound", - "用户信息更新成功!": "User information updated successfully!", - "模型倍率 %.2f,分组倍率 %.2f": "model rate %.2f, group rate %.2f", - "模型倍率 %.2f,分组倍率 %.2f,补全倍率 %.2f": "model rate %.2f, group rate %.2f, completion rate %.2f", - "使用明细(总消耗额度:{renderQuota(stat.quota)})": "Usage Details (Total Consumption Quota: {renderQuota(stat.quota)})", - "用户名称": "User Name", - "令牌名称": "Token Name", - "默认令牌": "Default Token", - "留空则查询全部用户": "Leave blank to query all users", - "留空则查询全部令牌": "Leave blank to query all tokens", - "模型名称": "Model Name", - "留空则查询全部模型": "Leave blank to query all models", - "起始时间": "Start Time", - "结束时间": "End Time", - "查询": "Query", - "提示": "Prompt", - "补全": "Completion", - "消耗额度": "Used Quota", - "可选值": "Optional Values", - "渠道不存在:%d": "Channel does not exist: %d", - "数据库一致性已被破坏,请联系管理员": "Database consistency has been broken, please contact the administrator", - "使用近似的方式估算 token 数以减少计算量": "Estimate the number of tokens in an approximate way to reduce computational load", - "请填写ChannelName和ChannelKey!": "Please fill in the ChannelName and ChannelKey!", - "请至少选择一个Model!": "Please select at least one Model!", - "加载首页内容失败": "Failed to load the homepage content", - "加载关于内容失败": "Failed to load the About content", - "兑换码更新成功!": "Redemption code updated successfully!", - "兑换码创建成功!": "Redemption code created successfully!", - "用户账户创建成功!": "User account created successfully!", - "生成数量": "Generate quantity", - "请输入生成数量": "Please enter the quantity to generate", - "创建新用户账户": "Create new user account", - "渠道更新成功!": "Channel updated successfully!", - "渠道创建成功!": "Channel created successfully!", - "请选择分组": "Please select a group", - "更新兑换码信息": "Update redemption code information", - "创建新的兑换码": "Create a new redemption code", - "请在系统设置页面编辑分组倍率以添加新的分组:": "Please edit the group ratio in the system settings page to add a new group:", - "未找到所请求的页面": "The requested page was not found", - "过期时间格式错误!": "Expiration time format error!", - "请输入过期时间,格式为 yyyy-MM-dd HH:mm:ss,-1 表示无限制": "Please enter the expiration time, the format is yyyy-MM-dd HH:mm:ss, -1 means no limit", - "此项可选,为一个 JSON 文本,键为用户请求的模型名称,值为要替换的模型名称,例如:": "This is optional, it's a JSON text, the key is the model name requested by the user, and the value is the model name to be replaced, for example:", - "此项可选,输入镜像站地址,格式为:": "This is optional, enter the mirror site address, the format is:", - "模型映射": "Model mapping", - "请输入默认 API 版本,例如:2023-03-15-preview,该配置可以被实际的请求查询参数所覆盖": "Please enter the default API version, for example: 2023-03-15-preview, this configuration can be overridden by the actual request query parameters", - "默认": "Default", - "图片演示": "Image demo", - "参数替换为你的部署名称(模型名称中的点会被剔除)": "Replace the parameter with your deployment name (dots in the model name will be removed)", - "模型映射必须是合法的 JSON 格式!": "Model mapping must be in valid JSON format!", - "取消无限额度": "Cancel unlimited quota", - "取消": "Cancel", - "请输入新的剩余额度": "Please enter the new remaining quota", - "请输入单个兑换码中包含的额度": "Please enter the quota included in a single redemption code", - "请输入用户名": "Please enter username", - "请输入显示名称": "Please enter display name", - "请输入密码": "Please enter password", - "模型部署名称必须和模型名称保持一致": "The model deployment name must be consistent with the model name", - ",因为 One API 会把请求体中的 model": ", because One API will take the model in the request body", - "请输入 AZURE_OPENAI_ENDPOINT": "Please enter AZURE_OPENAI_ENDPOINT", - "请输入自定义渠道的 Base URL": "Please enter the Base URL of the custom channel", - "Homepage URL 填": "Fill in the Homepage URL", - "Authorization callback URL 填": "Fill in the Authorization callback URL", - "请为渠道命名": "Please name the channel", - "此项可选,用于修改请求体中的模型名称,为一个 JSON 字符串,键为请求中模型名称,值为要替换的模型名称,例如:": "This is optional, used to modify the model name in the request body, it's a JSON string, the key is the model name in the request, and the value is the model name to be replaced, for example:", - "模型重定向": "Model redirection", - "请输入渠道对应的鉴权密钥": "Please enter the authentication key corresponding to the channel", - "注意,": "Note that, ", - ",图片演示。": "related image demo.", - "令牌创建成功,请在列表页面点击复制获取令牌!": "Token created successfully, please click copy on the list page to get the token!", - "代理": "Proxy", - "此项可选,用于通过代理站来进行 API 调用,请输入代理站地址,格式为:https://domain.com": "This is optional, used to make API calls through the proxy site, please enter the proxy site address, the format is: https://domain.com", - "取消密码登录将导致所有未绑定其他登录方式的用户(包括管理员)无法通过密码登录,确认取消?": "Canceling password login will cause all users (including administrators) who have not bound other login methods to be unable to log in via password, confirm cancel?", - "按照如下格式输入:": "Enter in the following format:", - "模型版本": "Model version", - "请输入星火大模型版本,注意是接口地址中的版本号,例如:v2.1": "Please enter the version of the Starfire model, note that it is the version number in the interface address, for example: v2.1", - "点击查看": "click to view", - "请确保已在 Azure 上创建了 gpt-35-turbo 模型,并且 apiVersion 已正确填写!": "Please make sure that the gpt-35-turbo model has been created on Azure, and the apiVersion has been filled in correctly!", - "处理中...": "Processing...", - "绑定成功!": "Binding successful!", - "登录成功!": "Login successful!", - "操作失败,重定向至登录界面中...": "Operation failed, redirecting to login screen...", - "出现错误,第 ${count} 次重试中...": "An error occurred, retrying ${count}...", - "首页": "Home", - "渠道": "Channel", - "令牌": "API Keys", - "兑换": "Redeem", - "充值": "Recharge", - "用户": "Users", - "日志": "Logs", - "设置": "Settings", - "关于": "About", - "聊天": "Chat", - "注销成功!": "Logout successful!", - "注销": "Log out", - "登录": "Log in", - "注册": "Sign up", - "加载{name}中...": "Loading {name}...", - "未登录或登录已过期,请重新登录!": "Not logged in or login has expired, please log in again!", - "请立刻修改默认密码!": "Please change the default password immediately!", - "欢迎回来": "Welcome back", - "没有账户?": "No account?", - "立刻注册": "Sign up now", - "用户名": "Username", - "密码": "Password", - "正在登录……": "Logging in...", - "忘记密码": "Forgot password", - "其他方式": "Other methods", - "微信扫码关注公众号,输入「验证码」获取验证码(三分钟内有效)": "Scan the QR code with WeChat, follow the official account and enter 'verification code' to get the verification code (valid within three minutes)", - "验证码": "Verification code", - "全部用户": "All users", - "当前用户": "Current user", - "全部": "All", - "消费": "Consumption", - "管理": "Management", - "系统": "System", - "未知": "Unknown", - "其他模型": "Other models", - "复制成功": "Copy successful", - "使用明细": "Usages", - "刷新": "Refresh", - "收起面板": "Collapse panel", - "展开面板": "Expand panel", - "显示查询选项": "Show search options", - "隐藏查询选项": "Hide search options", - "用户名称": "User name", - "可选值": "Optional values", - "渠道 ID": "Channel ID", - "令牌名称": "Key name", - "模型名称": "Model name", - "起始时间": "Start time", - "结束时间": "End time", - "查询": "Query", - "隐藏条形图": "Hide bar chart", - "显示条形图": "Show bar chart", - "折线条形图只展示最新50条数据": "Line and bar charts only show the latest 50 pieces of data", - "总消耗": "Total consumption", - "总共调用了 {payload[0].value} 次": "A total of {payload[0].value} calls were made", - "{model.name}: {model.value} 次": "{model.name}: {model.value} times", - "总共调用了 {payload[0].value} 次 {payload[0].name}": "A total of {payload[0].value} {payload[0].name} calls were made", - "总消耗额度": "Total consumption limit", - "暂无数据": "No data available", - "更多数据统计图形即将到来,敬请期待!": "More data statistics graphics are coming soon, stay tuned!", - "复制用户名": "Copy username", - "{`共 ${counts} 条数据`}": "{`A total of ${counts} pieces of data`}", - "共 0 条数据": "A total of 0 pieces of data", - "选择明细分类": "Select detail category", - "模型倍率": "model rate", - "分组倍率": "group rate", - "新密码已复制到剪贴板:": "New password has been copied to the clipboard:", - "密码重置确认": "Password reset confirmation", - "邮箱地址": "Email address", - "新密码": "New password", - "密码已复制到剪贴板:": "Password has been copied to the clipboard:", - "密码重置完成": "Password reset complete", - "提交": "Submit", - "返回登录": "Return to login", - "请稍后重试,浏览器环境检查未通过": "Please try again later, browser environment check failed", - "重置邮件发送成功,请检查邮箱!": "Reset email sent successfully, please check your email!", - "密码重置": "Password reset", - "重试": "Retry", - "组": "Group", - "令牌已重置并已复制到剪贴板": "Token has been reset and copied to the clipboard", - "邀请链接已复制到剪切板": "Invitation link has been copied to the clipboard", - "系统令牌已复制到剪切板": "System token has been copied to the clipboard", - "请输入你的账户名以确认删除!": "Please enter your account name to confirm deletion!", - "账户已删除!": "Account has been deleted!", - "微信账户绑定成功!": "WeChat account binding successful!", - "请稍后几秒重试,Turnstile 正在检查用户环境!": "Please try again in a few seconds, Turnstile is checking the user environment!", - "验证码发送成功,请检查邮箱!": "Verification code sent successfully, please check your email!", - "邮箱账户绑定成功!": "Email account binding successful!", - "个人信息": "Personal information", - "编辑个人信息": "Edit personal information", - "生成系统访问令牌": "Generate system access token", - "复制邀请链接": "Copy invitation link", - "删除个人帐户": "Delete personal account", - "普通用户": "Regular user", - "管理员": "Administrator", - "超级管理员": "Super administrator", - "显示名称": "Display name", - "GitHub 账号": "GitHub account", - "微信账号": "WeChat account", - "修改个人信息只允许在电脑端进行。生成的令牌用于系统管理,而非用于请求 OpenAI 相关的服务,请知悉。": "Modifying personal information is only allowed on a computer. The generated token is for system management, not for requesting OpenAI related services. Please be aware.", - "可用模型": "Available models", - "账号绑定": "Account binding", - "绑定微信": "Bind WeChat", - "绑定 GitHub": "Bind GitHub", - "绑定邮箱": "Bind Email", - "绑定": "Bind", - "绑定邮箱地址": "Bind email address", - "输入邮箱地址": "Enter email address", - "重新发送": "Resend", - "获取验证码": "Get verification code", - "确认绑定": "Confirm binding", - "取消": "Cancel", - "危险操作": "Dangerous operation", - "您正在删除自己的帐户,将清空所有数据且不可恢复": "You are deleting your own account, all data will be cleared and cannot be recovered", - "输入你的账户名": "Enter your account name", - "以确认删除": "To confirm deletion", - "确认删除": "Confirm deletion", - "未使用": "Not used", - "已禁用": "Disabled", - "已使用": "Used", - "未知状态": "Unknown status", - "操作成功完成!": "Operation successfully completed!", - "搜索兑换码的 ID 和名称 ...": "Search for the ID and name of the redemption code ...", - "名称": "Name", - "状态": "Status", - "额度": "Quota", - "创建时间": "Creation time", - "兑换时间": "Redemption time", - "操作": "Operation", - "尚未兑换": "Not yet redeemed", - "已复制到剪贴板!": "Copied to clipboard!", - "无法复制到剪贴板,请手动复制,已将兑换码填入搜索框。": "Unable to copy to clipboard, please copy manually. The redemption code has been filled in the search box.", - "复制": "Copy", - "删除": "Delete", - "禁用": "Disable", - "启用": "Enable", - "编辑": "Edit", - "添加新的兑换码": "Add new redemption code", - "密码长度不得小于 8 位!": "Password length must not be less than 8 characters!", - "两次输入的密码不一致": "The two passwords entered do not match", - "注册成功!": "Registration successful!", - "请填写注册邮箱!": "Please fill in the registration email!", - "请在${verificationTimeout}秒后再试": "Please try again after ${verificationTimeout} seconds", - "验证码发送成功,请检查你的邮箱!": "Verification code sent successfully, please check your email!", - "已有账户?": "Already have an account?", - "请输入用户名(最长 12 位)": "Please enter a username (up to 12 characters)", - "请输入密码(最短 8 位,最长 20 位)": "Please enter a password (minimum 8 characters, maximum 20 characters)", - "请再次输入密码": "Please enter the password again", - "请输入邮箱地址": "Please enter an email address", - "秒后可重发": "Can be resent after seconds", - "请输入邮箱验证码": "Please enter the email verification code", - "已过期": "Expired", - "已启用": "Enabled", - "已耗尽": "Exhausted", - "无": "None", - "令牌密钥": "API Key", - "令牌状态": "Key status", - "已用额度": "Used quota", - "剩余额度": "Remaining quota", - "过期时间": "Expiration time", - "你确定要删除这个令牌吗?": "Are you sure you want to delete this key?", - "无法复制到剪贴板,请手动复制,已将令牌密钥填入搜索框": "Unable to copy to clipboard, please copy manually. The key key has been filled in the search box.", - "无限制": "Unlimited", - "永不过期": "Never expires", - "使用 API 访问令牌进行服务鉴权和计费。": "Use API Key for service authentication and billing.", - "API 访问令牌关系到您的个人利益,请妥善留存,不要与其他人共享,也不要保存在客户端代码中。": "API Key is related to your personal interests. Please keep it properly. Do not share it with others or save it in client code.", - "创建令牌": "Create Key", - "什么都还没有,快去创建一个令牌开始使用吧!": "Nothing yet, go create a key to start using!", - "你确定要删除该令牌吗": "Are you sure you want to delete this key", - "导出令牌信息": "Export key information", - "错误:未登录或登录已过期,请重新登录!": "Error: Not logged in or login has expired, please log in again!", - "错误:请求次数过多,请稍后再试!": "Error: Too many requests, please try again later!", - "错误:服务器内部错误,请联系管理员!": "Error: Server internal error, please contact the online customer service!", - "本站仅作演示之用,无服务端!": "This site is for demonstration purposes only, no server!", - "错误:": "Error:", - "加载首页内容失败...": "Failed to load homepage content...", - "系统状况": "System status", - "系统信息": "System information", - "系统信息总览": "System information overview", - "名称:": "Name:", - "版本:": "Version:", - "源码:": "Source code:", - "启动时间:": "Startup time:", - "系统配置": "System configuration", - "系统配置总览": "System configuration overview", - "邮箱验证:": "Email verification:", - "未启用": "Not enabled", - "Turnstile 用户校验:": "Turnstile user verification:", - "页面不存在": "Page does not exist", - "请检查你的浏览器地址是否正确": "Please check if your browser address is correct", - "个人设置": "Personal settings", - "运营设置": "Operations settings", - "系统设置": "System settings", - "其他设置": "Other settings", - "默认令牌": "Default key", - "过期时间必须在当前时间之后!": "Expiration time must be after the current time!", - "额度必须大于等于 0!": "Quota must be greater than or equal to 0!", - "过期时间格式错误!": "Expiration time format error!", - "创建令牌数量必须大于等于 1!": "The number of keys to create must be greater than or equal to 1!", - "令牌修改成功": "API Key modification successful", - "令牌创建成功": "API Key creation successful", - "更新令牌信息": "Update key information", - "创建新的令牌": "Create a new key", - "请输入名称": "Please enter a name", - "请输入过期时间,格式为 yyyy-MM-dd HH:mm:ss,-1 表示无限制": "Please enter the expiration time, the format is yyyy-MM-dd HH:mm:ss, -1 means unlimited", - "无限额度": "Unlimited quota", - "注意:启用无限额度后,已用额度将不再进行计算。": "Note: After enabling unlimited quota, the used quota will no longer be calculated.", - "等于": "Equals", - "请输入额度(单位:token)": "Please enter the quota (unit: token)", - "创建令牌数量": "Create key quantity", - "请输入令牌数量": "Please enter the number of keys", - "注意:令牌的额度仅用于限制令牌本身的最大额度使用量,实际的使用受到账户的剩余额度限制。": "Note: The quota of the key is only used to limit the maximum quota usage of the key itself, and the actual usage is subject to the remaining quota of the account.", - "我的令牌": "My keys", - "请输入额度兑换码!": "Please enter the redeem code!", - "充值成功!": "Recharge successful!", - "请求失败": "Request failed", - "超级管理员未设置充值链接!": "The super administrator did not set a recharge link!", - "充值额度": "Recharge quota", - "兑换中...": "Redeeming...", - "请点击充值以获取额度兑换码。": "Please click recharge to get the quota redemption code.", - "用户信息更新成功!": "User information updated successfully!", - "更新用户信息": "Update user information", - "请输入新的用户名": "Please enter a new username", - "请输入新的密码,最短 8 位": "Please enter a new password, at least 8 characters", - "请输入新的显示名称": "Please enter a new display name", - "分组": "Group", - "请选择分组": "Please select a group", - "请在系统设置页面编辑分组倍率以添加新的分组:": "Please edit the group rate on the system settings page to add a new group:", - "请输入新的剩余额度": "Please enter a new remaining quota", - "已绑定的 GitHub 账户": "Bound GitHub account", - "此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改": "This item is read-only, users need to bind through the relevant binding button on the personal settings page, cannot be directly modified", - "已绑定的微信账户": "Bound WeChat account", - "已绑定的邮箱账户": "Bound email account", - "新版本可用:${data.version},请使用快捷键 Shift + F5 刷新页面": "New version available: ${data.version}, please refresh the page using the shortcut key Shift + F5", - "无法正常连接至服务器!": "Unable to connect to the server normally!", - "提示:": "Input:", - "补全:": "Output:", - "搜索令牌名称": "Search key name", - "测试所有渠道": "Test all channels", - "更新已启用渠道余额": "Update the balance of enabled channels" -} diff --git a/i18n/translate.py b/i18n/translate.py deleted file mode 100644 index 6ba9bc5d..00000000 --- a/i18n/translate.py +++ /dev/null @@ -1,61 +0,0 @@ -import argparse -import json -import os - -def list_file_paths(path): - file_paths = [] - for root, dirs, files in os.walk(path): - if "node_modules" in dirs: - dirs.remove("node_modules") - if "build" in dirs: - dirs.remove("build") - if "i18n" in dirs: - dirs.remove("i18n") - for file in files: - file_path = os.path.join(root, file) - if file_path.endswith("png") or file_path.endswith("ico") or file_path.endswith("db") or file_path.endswith("exe"): - continue - file_paths.append(file_path) - - for dir in dirs: - dir_path = os.path.join(root, dir) - file_paths += list_file_paths(dir_path) - - return file_paths - - -def replace_keys_in_repository(repo_path, json_file_path): - with open(json_file_path, 'r', encoding="utf-8") as json_file: - key_value_pairs = json.load(json_file) - - pairs = [] - for key, value in key_value_pairs.items(): - pairs.append((key, value)) - pairs.sort(key=lambda x: len(x[0]), reverse=True) - - files = list_file_paths(repo_path) - print('Total files: {}'.format(len(files))) - for file_path in files: - replace_keys_in_file(file_path, pairs) - - -def replace_keys_in_file(file_path, pairs): - try: - with open(file_path, 'r', encoding="utf-8") as file: - content = file.read() - - for key, value in pairs: - content = content.replace(key, value) - - with open(file_path, 'w', encoding="utf-8") as file: - file.write(content) - except UnicodeDecodeError: - print('UnicodeDecodeError: {}'.format(file_path)) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description='Replace keys in repository.') - parser.add_argument('--repository_path', help='Path to repository') - parser.add_argument('--json_file_path', help='Path to JSON file') - args = parser.parse_args() - replace_keys_in_repository(args.repository_path, args.json_file_path) diff --git a/main.go b/main.go index 67a3cd95..35c2764e 100644 --- a/main.go +++ b/main.go @@ -3,21 +3,24 @@ package main import ( "embed" "fmt" + "os" + "strconv" + "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" "github.com/gin-gonic/gin" _ "github.com/joho/godotenv/autoload" + "github.com/songquanpeng/one-api/common" "github.com/songquanpeng/one-api/common/client" "github.com/songquanpeng/one-api/common/config" + "github.com/songquanpeng/one-api/common/i18n" "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/controller" "github.com/songquanpeng/one-api/middleware" "github.com/songquanpeng/one-api/model" "github.com/songquanpeng/one-api/relay/adaptor/openai" "github.com/songquanpeng/one-api/router" - "os" - "strconv" ) //go:embed web/build/* @@ -91,12 +94,18 @@ func main() { openai.InitTokenEncoders() client.Init() + // Initialize i18n + if err := i18n.Init(); err != nil { + logger.FatalLog("failed to initialize i18n: " + err.Error()) + } + // Initialize HTTP server server := gin.New() server.Use(gin.Recovery()) // This will cause SSE not to work!!! //server.Use(gzip.Gzip(gzip.DefaultCompression)) server.Use(middleware.RequestId()) + server.Use(middleware.Language()) middleware.SetUpLogger(server) // Initialize session store store := cookie.NewStore([]byte(config.SessionSecret)) diff --git a/middleware/distributor.go b/middleware/distributor.go index 0aceb29d..58ae0556 100644 --- a/middleware/distributor.go +++ b/middleware/distributor.go @@ -2,13 +2,15 @@ package middleware import ( "fmt" + "net/http" + "strconv" + "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common/ctxkey" "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/model" "github.com/songquanpeng/one-api/relay/channeltype" - "net/http" - "strconv" ) type ModelRequest struct { @@ -17,6 +19,7 @@ type ModelRequest struct { func Distribute() func(c *gin.Context) { return func(c *gin.Context) { + ctx := c.Request.Context() userId := c.GetInt(ctxkey.Id) userGroup, _ := model.CacheGetUserGroup(userId) c.Set(ctxkey.Group, userGroup) @@ -52,6 +55,7 @@ func Distribute() func(c *gin.Context) { return } } + logger.Debugf(ctx, "user id %d, user group: %s, request model: %s, using channel #%d", userId, userGroup, requestModel, channel.Id) SetupContextForSelectedChannel(c, channel, requestModel) c.Next() } diff --git a/middleware/language.go b/middleware/language.go new file mode 100644 index 00000000..c8585bae --- /dev/null +++ b/middleware/language.go @@ -0,0 +1,25 @@ +package middleware + +import ( + "strings" + + "github.com/gin-gonic/gin" + + "github.com/songquanpeng/one-api/common/i18n" +) + +func Language() gin.HandlerFunc { + return func(c *gin.Context) { + lang := c.GetHeader("Accept-Language") + if lang == "" { + lang = "en" + } + if strings.HasPrefix(strings.ToLower(lang), "zh") { + lang = "zh-CN" + } else { + lang = "en" + } + c.Set(i18n.ContextKey, lang) + c.Next() + } +} diff --git a/middleware/rate-limit.go b/middleware/rate-limit.go index c1be92f3..63d7d549 100644 --- a/middleware/rate-limit.go +++ b/middleware/rate-limit.go @@ -7,6 +7,7 @@ import ( "time" "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common" "github.com/songquanpeng/one-api/common/config" ) @@ -71,7 +72,7 @@ func memoryRateLimiter(c *gin.Context, maxRequestNum int, duration int64, mark s } func rateLimitFactory(maxRequestNum int, duration int64, mark string) func(c *gin.Context) { - if maxRequestNum == 0 { + if maxRequestNum == 0 || config.DebugEnabled { return func(c *gin.Context) { c.Next() } diff --git a/middleware/request-id.go b/middleware/request-id.go index bef09e32..973a63f8 100644 --- a/middleware/request-id.go +++ b/middleware/request-id.go @@ -1,8 +1,8 @@ package middleware import ( - "context" "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common/helper" ) @@ -10,7 +10,7 @@ func RequestId() func(c *gin.Context) { return func(c *gin.Context) { id := helper.GenRequestID() c.Set(helper.RequestIdKey, id) - ctx := context.WithValue(c.Request.Context(), helper.RequestIdKey, id) + ctx := helper.SetRequestID(c.Request.Context(), id) c.Request = c.Request.WithContext(ctx) c.Header(helper.RequestIdKey, id) c.Next() diff --git a/model/log.go b/model/log.go index 58fdd513..2c920652 100644 --- a/model/log.go +++ b/model/log.go @@ -4,26 +4,31 @@ import ( "context" "fmt" + "gorm.io/gorm" + "github.com/songquanpeng/one-api/common" "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/helper" "github.com/songquanpeng/one-api/common/logger" - "gorm.io/gorm" ) type Log struct { - Id int `json:"id"` - UserId int `json:"user_id" gorm:"index"` - CreatedAt int64 `json:"created_at" gorm:"bigint;index:idx_created_at_type"` - Type int `json:"type" gorm:"index:idx_created_at_type"` - Content string `json:"content"` - Username string `json:"username" gorm:"index:index_username_model_name,priority:2;default:''"` - TokenName string `json:"token_name" gorm:"index;default:''"` - ModelName string `json:"model_name" gorm:"index;index:index_username_model_name,priority:1;default:''"` - Quota int `json:"quota" gorm:"default:0"` - PromptTokens int `json:"prompt_tokens" gorm:"default:0"` - CompletionTokens int `json:"completion_tokens" gorm:"default:0"` - ChannelId int `json:"channel" gorm:"index"` + Id int `json:"id"` + UserId int `json:"user_id" gorm:"index"` + CreatedAt int64 `json:"created_at" gorm:"bigint;index:idx_created_at_type"` + Type int `json:"type" gorm:"index:idx_created_at_type"` + Content string `json:"content"` + Username string `json:"username" gorm:"index:index_username_model_name,priority:2;default:''"` + TokenName string `json:"token_name" gorm:"index;default:''"` + ModelName string `json:"model_name" gorm:"index;index:index_username_model_name,priority:1;default:''"` + Quota int `json:"quota" gorm:"default:0"` + PromptTokens int `json:"prompt_tokens" gorm:"default:0"` + CompletionTokens int `json:"completion_tokens" gorm:"default:0"` + ChannelId int `json:"channel" gorm:"index"` + RequestId string `json:"request_id" gorm:"default:''"` + ElapsedTime int64 `json:"elapsed_time" gorm:"default:0"` // unit is ms + IsStream bool `json:"is_stream" gorm:"default:false"` + SystemPromptReset bool `json:"system_prompt_reset" gorm:"default:false"` } const ( @@ -32,9 +37,21 @@ const ( LogTypeConsume LogTypeManage LogTypeSystem + LogTypeTest ) -func RecordLog(userId int, logType int, content string) { +func recordLogHelper(ctx context.Context, log *Log) { + requestId := helper.GetRequestID(ctx) + log.RequestId = requestId + err := LOG_DB.Create(log).Error + if err != nil { + logger.Error(ctx, "failed to record log: "+err.Error()) + return + } + logger.Infof(ctx, "record log: %+v", log) +} + +func RecordLog(ctx context.Context, userId int, logType int, content string) { if logType == LogTypeConsume && !config.LogConsumeEnabled { return } @@ -45,13 +62,10 @@ func RecordLog(userId int, logType int, content string) { Type: logType, Content: content, } - err := LOG_DB.Create(log).Error - if err != nil { - logger.SysError("failed to record log: " + err.Error()) - } + recordLogHelper(ctx, log) } -func RecordTopupLog(userId int, content string, quota int) { +func RecordTopupLog(ctx context.Context, userId int, content string, quota int) { log := &Log{ UserId: userId, Username: GetUsernameById(userId), @@ -60,34 +74,23 @@ func RecordTopupLog(userId int, content string, quota int) { Content: content, Quota: quota, } - err := LOG_DB.Create(log).Error - if err != nil { - logger.SysError("failed to record log: " + err.Error()) - } + recordLogHelper(ctx, log) } -func RecordConsumeLog(ctx context.Context, userId int, channelId int, promptTokens int, completionTokens int, modelName string, tokenName string, quota int64, content string) { - logger.Info(ctx, fmt.Sprintf("record consume log: userId=%d, channelId=%d, promptTokens=%d, completionTokens=%d, modelName=%s, tokenName=%s, quota=%d, content=%s", userId, channelId, promptTokens, completionTokens, modelName, tokenName, quota, content)) +func RecordConsumeLog(ctx context.Context, log *Log) { if !config.LogConsumeEnabled { return } - log := &Log{ - UserId: userId, - Username: GetUsernameById(userId), - CreatedAt: helper.GetTimestamp(), - Type: LogTypeConsume, - Content: content, - PromptTokens: promptTokens, - CompletionTokens: completionTokens, - TokenName: tokenName, - ModelName: modelName, - Quota: int(quota), - ChannelId: channelId, - } - err := LOG_DB.Create(log).Error - if err != nil { - logger.Error(ctx, "failed to record log: "+err.Error()) - } + log.Username = GetUsernameById(log.UserId) + log.CreatedAt = helper.GetTimestamp() + log.Type = LogTypeConsume + recordLogHelper(ctx, log) +} + +func RecordTestLog(ctx context.Context, log *Log) { + log.CreatedAt = helper.GetTimestamp() + log.Type = LogTypeTest + recordLogHelper(ctx, log) } func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int) (logs []*Log, err error) { diff --git a/model/redemption.go b/model/redemption.go index 45871a71..957a33be 100644 --- a/model/redemption.go +++ b/model/redemption.go @@ -1,11 +1,14 @@ package model import ( + "context" "errors" "fmt" + + "gorm.io/gorm" + "github.com/songquanpeng/one-api/common" "github.com/songquanpeng/one-api/common/helper" - "gorm.io/gorm" ) const ( @@ -48,7 +51,7 @@ func GetRedemptionById(id int) (*Redemption, error) { return &redemption, err } -func Redeem(key string, userId int) (quota int64, err error) { +func Redeem(ctx context.Context, key string, userId int) (quota int64, err error) { if key == "" { return 0, errors.New("未提供兑换码") } @@ -82,7 +85,7 @@ func Redeem(key string, userId int) (quota int64, err error) { if err != nil { return 0, errors.New("兑换失败," + err.Error()) } - RecordLog(userId, LogTypeTopup, fmt.Sprintf("通过兑换码充值 %s", common.LogQuota(redemption.Quota))) + RecordLog(ctx, userId, LogTypeTopup, fmt.Sprintf("通过兑换码充值 %s", common.LogQuota(redemption.Quota))) return redemption.Quota, nil } diff --git a/model/token.go b/model/token.go index 91e72a82..52ee63ef 100644 --- a/model/token.go +++ b/model/token.go @@ -3,12 +3,14 @@ package model import ( "errors" "fmt" + + "gorm.io/gorm" + "github.com/songquanpeng/one-api/common" "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/helper" "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/common/message" - "gorm.io/gorm" ) const ( @@ -238,16 +240,31 @@ func PreConsumeTokenQuota(tokenId int, quota int64) (err error) { if err != nil { logger.SysError("failed to fetch user email: " + err.Error()) } - prompt := "您的额度即将用尽" + prompt := "额度提醒" + var contentText string if noMoreQuota { - prompt = "您的额度已用尽" + contentText = "您的额度已用尽" + } else { + contentText = "您的额度即将用尽" } if email != "" { topUpLink := fmt.Sprintf("%s/topup", config.ServerAddress) - err = message.SendEmail(prompt, email, - fmt.Sprintf("%s,当前剩余额度为 %d,为了不影响您的使用,请及时充值。
充值链接:%s", prompt, userQuota, topUpLink, topUpLink)) + content := message.EmailTemplate( + prompt, + fmt.Sprintf(` +

您好!

+

%s,当前剩余额度为 %d

+

为了不影响您的使用,请及时充值。

+

+ 立即充值 +

+

如果按钮无法点击,请复制以下链接到浏览器中打开:

+

%s

+ `, contentText, userQuota, topUpLink, topUpLink), + ) + err = message.SendEmail(prompt, email, content) if err != nil { - logger.SysError("failed to send email" + err.Error()) + logger.SysError("failed to send email: " + err.Error()) } } }() diff --git a/model/user.go b/model/user.go index a964a0d7..021810c0 100644 --- a/model/user.go +++ b/model/user.go @@ -1,16 +1,19 @@ package model import ( + "context" "errors" "fmt" + "strings" + + "gorm.io/gorm" + "github.com/songquanpeng/one-api/common" "github.com/songquanpeng/one-api/common/blacklist" "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/helper" "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/common/random" - "gorm.io/gorm" - "strings" ) const ( @@ -92,7 +95,7 @@ func GetUserById(id int, selectAll bool) (*User, error) { if selectAll { err = DB.First(&user, "id = ?", id).Error } else { - err = DB.Omit("password").First(&user, "id = ?", id).Error + err = DB.Omit("password", "access_token").First(&user, "id = ?", id).Error } return &user, err } @@ -114,7 +117,7 @@ func DeleteUserById(id int) (err error) { return user.Delete() } -func (user *User) Insert(inviterId int) error { +func (user *User) Insert(ctx context.Context, inviterId int) error { var err error if user.Password != "" { user.Password, err = common.Password2Hash(user.Password) @@ -130,16 +133,16 @@ func (user *User) Insert(inviterId int) error { return result.Error } if config.QuotaForNewUser > 0 { - RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", common.LogQuota(config.QuotaForNewUser))) + RecordLog(ctx, user.Id, LogTypeSystem, fmt.Sprintf("新用户注册赠送 %s", common.LogQuota(config.QuotaForNewUser))) } if inviterId != 0 { if config.QuotaForInvitee > 0 { _ = IncreaseUserQuota(user.Id, config.QuotaForInvitee) - RecordLog(user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", common.LogQuota(config.QuotaForInvitee))) + RecordLog(ctx, user.Id, LogTypeSystem, fmt.Sprintf("使用邀请码赠送 %s", common.LogQuota(config.QuotaForInvitee))) } if config.QuotaForInviter > 0 { _ = IncreaseUserQuota(inviterId, config.QuotaForInviter) - RecordLog(inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", common.LogQuota(config.QuotaForInviter))) + RecordLog(ctx, inviterId, LogTypeSystem, fmt.Sprintf("邀请用户赠送 %s", common.LogQuota(config.QuotaForInviter))) } } // create default token diff --git a/monitor/channel.go b/monitor/channel.go index 7e5dc58a..a375c8db 100644 --- a/monitor/channel.go +++ b/monitor/channel.go @@ -2,6 +2,7 @@ package monitor import ( "fmt" + "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/common/message" @@ -30,17 +31,32 @@ func notifyRootUser(subject string, content string) { func DisableChannel(channelId int, channelName string, reason string) { model.UpdateChannelStatusById(channelId, model.ChannelStatusAutoDisabled) logger.SysLog(fmt.Sprintf("channel #%d has been disabled: %s", channelId, reason)) - subject := fmt.Sprintf("渠道「%s」(#%d)已被禁用", channelName, channelId) - content := fmt.Sprintf("渠道「%s」(#%d)已被禁用,原因:%s", channelName, channelId, reason) + subject := fmt.Sprintf("渠道状态变更提醒") + content := message.EmailTemplate( + subject, + fmt.Sprintf(` +

您好!

+

渠道「%s」(#%d)已被禁用。

+

禁用原因:

+

%s

+ `, channelName, channelId, reason), + ) notifyRootUser(subject, content) } func MetricDisableChannel(channelId int, successRate float64) { model.UpdateChannelStatusById(channelId, model.ChannelStatusAutoDisabled) logger.SysLog(fmt.Sprintf("channel #%d has been disabled due to low success rate: %.2f", channelId, successRate*100)) - subject := fmt.Sprintf("渠道 #%d 已被禁用", channelId) - content := fmt.Sprintf("该渠道(#%d)在最近 %d 次调用中成功率为 %.2f%%,低于阈值 %.2f%%,因此被系统自动禁用。", - channelId, config.MetricQueueSize, successRate*100, config.MetricSuccessRateThreshold*100) + subject := fmt.Sprintf("渠道状态变更提醒") + content := message.EmailTemplate( + subject, + fmt.Sprintf(` +

您好!

+

渠道 #%d 已被系统自动禁用。

+

禁用原因:

+

该渠道在最近 %d 次调用中成功率为 %.2f%%,低于系统阈值 %.2f%%

+ `, channelId, config.MetricQueueSize, successRate*100, config.MetricSuccessRateThreshold*100), + ) notifyRootUser(subject, content) } @@ -48,7 +64,14 @@ func MetricDisableChannel(channelId int, successRate float64) { func EnableChannel(channelId int, channelName string) { model.UpdateChannelStatusById(channelId, model.ChannelStatusEnabled) logger.SysLog(fmt.Sprintf("channel #%d has been enabled", channelId)) - subject := fmt.Sprintf("渠道「%s」(#%d)已被启用", channelName, channelId) - content := fmt.Sprintf("渠道「%s」(#%d)已被启用", channelName, channelId) + subject := fmt.Sprintf("渠道状态变更提醒") + content := message.EmailTemplate( + subject, + fmt.Sprintf(` +

您好!

+

渠道「%s」(#%d)已被重新启用。

+

您现在可以继续使用该渠道了。

+ `, channelName, channelId), + ) notifyRootUser(subject, content) } diff --git a/monitor/manage.go b/monitor/manage.go index 268d3924..338cd7c5 100644 --- a/monitor/manage.go +++ b/monitor/manage.go @@ -35,6 +35,8 @@ func ShouldDisableChannel(err *model.Error, statusCode int) bool { strings.Contains(lowerMessage, "balance") || strings.Contains(lowerMessage, "permission denied") || strings.Contains(lowerMessage, "organization has been restricted") || // groq + strings.Contains(lowerMessage, "api key not valid") || // gemini + strings.Contains(lowerMessage, "api key expired") || // gemini strings.Contains(lowerMessage, "已欠费") { return true } diff --git a/relay/adaptor/anthropic/constants.go b/relay/adaptor/anthropic/constants.go index 8ea7c4d8..9b515c1c 100644 --- a/relay/adaptor/anthropic/constants.go +++ b/relay/adaptor/anthropic/constants.go @@ -4,6 +4,7 @@ var ModelList = []string{ "claude-instant-1.2", "claude-2.0", "claude-2.1", "claude-3-haiku-20240307", "claude-3-5-haiku-20241022", + "claude-3-5-haiku-latest", "claude-3-sonnet-20240229", "claude-3-opus-20240229", "claude-3-5-sonnet-20240620", diff --git a/relay/adaptor/deepseek/constants.go b/relay/adaptor/deepseek/constants.go index ad840bc2..dc1a512a 100644 --- a/relay/adaptor/deepseek/constants.go +++ b/relay/adaptor/deepseek/constants.go @@ -2,5 +2,5 @@ package deepseek var ModelList = []string{ "deepseek-chat", - "deepseek-coder", + "deepseek-reasoner", } diff --git a/relay/adaptor/gemini/adaptor.go b/relay/adaptor/gemini/adaptor.go index a86fde40..e6e4d051 100644 --- a/relay/adaptor/gemini/adaptor.go +++ b/relay/adaptor/gemini/adaptor.go @@ -7,7 +7,7 @@ import ( "net/http" "github.com/gin-gonic/gin" - "github.com/songquanpeng/one-api/common/config" + "github.com/songquanpeng/one-api/common/helper" channelhelper "github.com/songquanpeng/one-api/relay/adaptor" "github.com/songquanpeng/one-api/relay/adaptor/openai" @@ -24,8 +24,13 @@ func (a *Adaptor) Init(meta *meta.Meta) { } func (a *Adaptor) GetRequestURL(meta *meta.Meta) (string, error) { - defaultVersion := config.GeminiVersion - if meta.ActualModelName == "gemini-2.0-flash-exp" { + var defaultVersion string + switch meta.ActualModelName { + case "gemini-2.0-flash-exp", + "gemini-2.0-flash-thinking-exp", + "gemini-2.0-flash-thinking-exp-01-21": + defaultVersion = "v1beta" + default: defaultVersion = "v1beta" } diff --git a/relay/adaptor/gemini/constants.go b/relay/adaptor/gemini/constants.go index 9d1cbc4a..381d0c12 100644 --- a/relay/adaptor/gemini/constants.go +++ b/relay/adaptor/gemini/constants.go @@ -7,5 +7,5 @@ var ModelList = []string{ "gemini-1.5-flash", "gemini-1.5-pro", "text-embedding-004", "aqa", "gemini-2.0-flash-exp", - "gemini-2.0-flash-thinking-exp", + "gemini-2.0-flash-thinking-exp", "gemini-2.0-flash-thinking-exp-01-21", } diff --git a/relay/adaptor/groq/constants.go b/relay/adaptor/groq/constants.go index 0864ebe7..2a26b28b 100644 --- a/relay/adaptor/groq/constants.go +++ b/relay/adaptor/groq/constants.go @@ -3,7 +3,6 @@ package groq // https://console.groq.com/docs/models var ModelList = []string{ - "gemma-7b-it", "gemma2-9b-it", "llama-3.1-70b-versatile", "llama-3.1-8b-instant", @@ -11,7 +10,6 @@ var ModelList = []string{ "llama-3.2-11b-vision-preview", "llama-3.2-1b-preview", "llama-3.2-3b-preview", - "llama-3.2-11b-vision-preview", "llama-3.2-90b-text-preview", "llama-3.2-90b-vision-preview", "llama-guard-3-8b", @@ -24,4 +22,6 @@ var ModelList = []string{ "distil-whisper-large-v3-en", "whisper-large-v3", "whisper-large-v3-turbo", + "deepseek-r1-distill-llama-70b-specdec", + "deepseek-r1-distill-llama-70b", } diff --git a/relay/adaptor/openai/token.go b/relay/adaptor/openai/token.go index 7c8468b9..b50220e7 100644 --- a/relay/adaptor/openai/token.go +++ b/relay/adaptor/openai/token.go @@ -3,14 +3,16 @@ package openai import ( "errors" "fmt" + "math" + "strings" + "github.com/pkoukk/tiktoken-go" + "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/image" "github.com/songquanpeng/one-api/common/logger" billingratio "github.com/songquanpeng/one-api/relay/billing/ratio" "github.com/songquanpeng/one-api/relay/model" - "math" - "strings" ) // tokenEncoderMap won't grow after initialization @@ -21,7 +23,8 @@ func InitTokenEncoders() { logger.SysLog("initializing token encoders") gpt35TokenEncoder, err := tiktoken.EncodingForModel("gpt-3.5-turbo") if err != nil { - logger.FatalLog(fmt.Sprintf("failed to get gpt-3.5-turbo token encoder: %s", err.Error())) + logger.FatalLog(fmt.Sprintf("failed to get gpt-3.5-turbo token encoder: %s, "+ + "if you are using in offline environment, please set TIKTOKEN_CACHE_DIR to use exsited files, check this link for more information: https://stackoverflow.com/questions/76106366/how-to-use-tiktoken-in-offline-mode-computer ", err.Error())) } defaultTokenEncoder = gpt35TokenEncoder gpt4oTokenEncoder, err := tiktoken.EncodingForModel("gpt-4o") diff --git a/relay/adaptor/tencent/adaptor.go b/relay/adaptor/tencent/adaptor.go index 0de92d4a..b20d4279 100644 --- a/relay/adaptor/tencent/adaptor.go +++ b/relay/adaptor/tencent/adaptor.go @@ -2,16 +2,19 @@ package tencent import ( "errors" + "io" + "net/http" + "strconv" + "strings" + "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common/helper" "github.com/songquanpeng/one-api/relay/adaptor" "github.com/songquanpeng/one-api/relay/adaptor/openai" "github.com/songquanpeng/one-api/relay/meta" "github.com/songquanpeng/one-api/relay/model" - "io" - "net/http" - "strconv" - "strings" + "github.com/songquanpeng/one-api/relay/relaymode" ) // https://cloud.tencent.com/document/api/1729/101837 @@ -52,10 +55,18 @@ func (a *Adaptor) ConvertRequest(c *gin.Context, relayMode int, request *model.G if err != nil { return nil, err } - tencentRequest := ConvertRequest(*request) + var convertedRequest any + switch relayMode { + case relaymode.Embeddings: + a.Action = "GetEmbedding" + convertedRequest = ConvertEmbeddingRequest(*request) + default: + a.Action = "ChatCompletions" + convertedRequest = ConvertRequest(*request) + } // we have to calculate the sign here - a.Sign = GetSign(*tencentRequest, a, secretId, secretKey) - return tencentRequest, nil + a.Sign = GetSign(convertedRequest, a, secretId, secretKey) + return convertedRequest, nil } func (a *Adaptor) ConvertImageRequest(request *model.ImageRequest) (any, error) { @@ -75,7 +86,12 @@ func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, meta *meta.Met err, responseText = StreamHandler(c, resp) usage = openai.ResponseText2Usage(responseText, meta.ActualModelName, meta.PromptTokens) } else { - err, usage = Handler(c, resp) + switch meta.Mode { + case relaymode.Embeddings: + err, usage = EmbeddingHandler(c, resp) + default: + err, usage = Handler(c, resp) + } } return } diff --git a/relay/adaptor/tencent/constants.go b/relay/adaptor/tencent/constants.go index e8631e5f..7997bfd6 100644 --- a/relay/adaptor/tencent/constants.go +++ b/relay/adaptor/tencent/constants.go @@ -6,4 +6,5 @@ var ModelList = []string{ "hunyuan-standard-256K", "hunyuan-pro", "hunyuan-vision", + "hunyuan-embedding", } diff --git a/relay/adaptor/tencent/main.go b/relay/adaptor/tencent/main.go index 827c8a46..8bf8e469 100644 --- a/relay/adaptor/tencent/main.go +++ b/relay/adaptor/tencent/main.go @@ -8,7 +8,6 @@ import ( "encoding/json" "errors" "fmt" - "github.com/songquanpeng/one-api/common/render" "io" "net/http" "strconv" @@ -16,11 +15,14 @@ import ( "time" "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common" "github.com/songquanpeng/one-api/common/conv" + "github.com/songquanpeng/one-api/common/ctxkey" "github.com/songquanpeng/one-api/common/helper" "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/common/random" + "github.com/songquanpeng/one-api/common/render" "github.com/songquanpeng/one-api/relay/adaptor/openai" "github.com/songquanpeng/one-api/relay/constant" "github.com/songquanpeng/one-api/relay/model" @@ -44,8 +46,68 @@ func ConvertRequest(request model.GeneralOpenAIRequest) *ChatRequest { } } +func ConvertEmbeddingRequest(request model.GeneralOpenAIRequest) *EmbeddingRequest { + return &EmbeddingRequest{ + InputList: request.ParseInput(), + } +} + +func EmbeddingHandler(c *gin.Context, resp *http.Response) (*model.ErrorWithStatusCode, *model.Usage) { + var tencentResponseP EmbeddingResponseP + err := json.NewDecoder(resp.Body).Decode(&tencentResponseP) + if err != nil { + return openai.ErrorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError), nil + } + + err = resp.Body.Close() + if err != nil { + return openai.ErrorWrapper(err, "close_response_body_failed", http.StatusInternalServerError), nil + } + + tencentResponse := tencentResponseP.Response + if tencentResponse.Error.Code != "" { + return &model.ErrorWithStatusCode{ + Error: model.Error{ + Message: tencentResponse.Error.Message, + Code: tencentResponse.Error.Code, + }, + StatusCode: resp.StatusCode, + }, nil + } + requestModel := c.GetString(ctxkey.RequestModel) + fullTextResponse := embeddingResponseTencent2OpenAI(&tencentResponse) + fullTextResponse.Model = requestModel + jsonResponse, err := json.Marshal(fullTextResponse) + if err != nil { + return openai.ErrorWrapper(err, "marshal_response_body_failed", http.StatusInternalServerError), nil + } + c.Writer.Header().Set("Content-Type", "application/json") + c.Writer.WriteHeader(resp.StatusCode) + _, err = c.Writer.Write(jsonResponse) + return nil, &fullTextResponse.Usage +} + +func embeddingResponseTencent2OpenAI(response *EmbeddingResponse) *openai.EmbeddingResponse { + openAIEmbeddingResponse := openai.EmbeddingResponse{ + Object: "list", + Data: make([]openai.EmbeddingResponseItem, 0, len(response.Data)), + Model: "hunyuan-embedding", + Usage: model.Usage{TotalTokens: response.EmbeddingUsage.TotalTokens}, + } + + for _, item := range response.Data { + openAIEmbeddingResponse.Data = append(openAIEmbeddingResponse.Data, openai.EmbeddingResponseItem{ + Object: item.Object, + Index: item.Index, + Embedding: item.Embedding, + }) + } + return &openAIEmbeddingResponse +} + func responseTencent2OpenAI(response *ChatResponse) *openai.TextResponse { fullTextResponse := openai.TextResponse{ + Id: response.ReqID, Object: "chat.completion", Created: helper.GetTimestamp(), Usage: model.Usage{ @@ -148,7 +210,7 @@ func Handler(c *gin.Context, resp *http.Response) (*model.ErrorWithStatusCode, * return openai.ErrorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError), nil } TencentResponse = responseP.Response - if TencentResponse.Error.Code != 0 { + if TencentResponse.Error.Code != "" { return &model.ErrorWithStatusCode{ Error: model.Error{ Message: TencentResponse.Error.Message, @@ -195,7 +257,7 @@ func hmacSha256(s, key string) string { return string(hashed.Sum(nil)) } -func GetSign(req ChatRequest, adaptor *Adaptor, secId, secKey string) string { +func GetSign(req any, adaptor *Adaptor, secId, secKey string) string { // build canonical request string host := "hunyuan.tencentcloudapi.com" httpRequestMethod := "POST" diff --git a/relay/adaptor/tencent/model.go b/relay/adaptor/tencent/model.go index fb97724e..fda6c6cc 100644 --- a/relay/adaptor/tencent/model.go +++ b/relay/adaptor/tencent/model.go @@ -35,16 +35,16 @@ type ChatRequest struct { // 1. 影响输出文本的多样性,取值越大,生成文本的多样性越强。 // 2. 取值区间为 [0.0, 1.0],未传值时使用各模型推荐值。 // 3. 非必要不建议使用,不合理的取值会影响效果。 - TopP *float64 `json:"TopP"` + TopP *float64 `json:"TopP,omitempty"` // 说明: // 1. 较高的数值会使输出更加随机,而较低的数值会使其更加集中和确定。 // 2. 取值区间为 [0.0, 2.0],未传值时使用各模型推荐值。 // 3. 非必要不建议使用,不合理的取值会影响效果。 - Temperature *float64 `json:"Temperature"` + Temperature *float64 `json:"Temperature,omitempty"` } type Error struct { - Code int `json:"Code"` + Code string `json:"Code"` Message string `json:"Message"` } @@ -61,15 +61,41 @@ type ResponseChoices struct { } type ChatResponse struct { - Choices []ResponseChoices `json:"Choices,omitempty"` // 结果 - Created int64 `json:"Created,omitempty"` // unix 时间戳的字符串 - Id string `json:"Id,omitempty"` // 会话 id - Usage Usage `json:"Usage,omitempty"` // token 数量 - Error Error `json:"Error,omitempty"` // 错误信息 注意:此字段可能返回 null,表示取不到有效值 - Note string `json:"Note,omitempty"` // 注释 - ReqID string `json:"Req_id,omitempty"` // 唯一请求 Id,每次请求都会返回。用于反馈接口入参 + Choices []ResponseChoices `json:"Choices,omitempty"` // 结果 + Created int64 `json:"Created,omitempty"` // unix 时间戳的字符串 + Id string `json:"Id,omitempty"` // 会话 id + Usage Usage `json:"Usage,omitempty"` // token 数量 + Error Error `json:"Error,omitempty"` // 错误信息 注意:此字段可能返回 null,表示取不到有效值 + Note string `json:"Note,omitempty"` // 注释 + ReqID string `json:"RequestId,omitempty"` // 唯一请求 Id,每次请求都会返回。用于反馈接口入参 } type ChatResponseP struct { Response ChatResponse `json:"Response,omitempty"` } + +type EmbeddingRequest struct { + InputList []string `json:"InputList"` +} + +type EmbeddingData struct { + Embedding []float64 `json:"Embedding"` + Index int `json:"Index"` + Object string `json:"Object"` +} + +type EmbeddingUsage struct { + PromptTokens int `json:"PromptTokens"` + TotalTokens int `json:"TotalTokens"` +} + +type EmbeddingResponse struct { + Data []EmbeddingData `json:"Data"` + EmbeddingUsage EmbeddingUsage `json:"Usage,omitempty"` + RequestId string `json:"RequestId,omitempty"` + Error Error `json:"Error,omitempty"` +} + +type EmbeddingResponseP struct { + Response EmbeddingResponse `json:"Response,omitempty"` +} diff --git a/relay/adaptor/vertexai/gemini/adapter.go b/relay/adaptor/vertexai/gemini/adapter.go index b5377875..1240ea5b 100644 --- a/relay/adaptor/vertexai/gemini/adapter.go +++ b/relay/adaptor/vertexai/gemini/adapter.go @@ -18,7 +18,8 @@ var ModelList = []string{ "gemini-pro", "gemini-pro-vision", "gemini-1.5-pro-001", "gemini-1.5-flash-001", "gemini-1.5-pro-002", "gemini-1.5-flash-002", - "gemini-2.0-flash-exp", "gemini-2.0-flash-thinking-exp", + "gemini-2.0-flash-exp", + "gemini-2.0-flash-thinking-exp", "gemini-2.0-flash-thinking-exp-01-21", } type Adaptor struct { diff --git a/relay/adaptor/zhipu/constants.go b/relay/adaptor/zhipu/constants.go index e1192123..a86ffc42 100644 --- a/relay/adaptor/zhipu/constants.go +++ b/relay/adaptor/zhipu/constants.go @@ -1,7 +1,14 @@ package zhipu +// https://open.bigmodel.cn/pricing + var ModelList = []string{ - "chatglm_turbo", "chatglm_pro", "chatglm_std", "chatglm_lite", - "glm-4", "glm-4v", "glm-3-turbo", "embedding-2", - "cogview-3", + "glm-zero-preview", "glm-4-plus", "glm-4-0520", "glm-4-airx", + "glm-4-air", "glm-4-long", "glm-4-flashx", "glm-4-flash", + "glm-4", "glm-3-turbo", + "glm-4v-plus", "glm-4v", "glm-4v-flash", + "cogview-3-plus", "cogview-3", "cogview-3-flash", + "cogviewx", "cogviewx-flash", + "charglm-4", "emohaa", "codegeex-4", + "embedding-2", "embedding-3", } diff --git a/relay/billing/billing.go b/relay/billing/billing.go index a99d37ee..2f87dfaf 100644 --- a/relay/billing/billing.go +++ b/relay/billing/billing.go @@ -3,6 +3,7 @@ package billing import ( "context" "fmt" + "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/model" ) @@ -31,8 +32,17 @@ func PostConsumeQuota(ctx context.Context, tokenId int, quotaDelta int64, totalQ } // totalQuota is total quota consumed if totalQuota != 0 { - logContent := fmt.Sprintf("模型倍率 %.2f,分组倍率 %.2f", modelRatio, groupRatio) - model.RecordConsumeLog(ctx, userId, channelId, int(totalQuota), 0, modelName, tokenName, totalQuota, logContent) + logContent := fmt.Sprintf("倍率:%.2f × %.2f", modelRatio, groupRatio) + model.RecordConsumeLog(ctx, &model.Log{ + UserId: userId, + ChannelId: channelId, + PromptTokens: int(totalQuota), + CompletionTokens: 0, + ModelName: modelName, + TokenName: tokenName, + Quota: int(totalQuota), + Content: logContent, + }) model.UpdateUserUsedQuotaAndRequestCount(userId, totalQuota) model.UpdateChannelUsedQuota(channelId, totalQuota) } diff --git a/relay/billing/ratio/model.go b/relay/billing/ratio/model.go index f83aa70c..d4deff8b 100644 --- a/relay/billing/ratio/model.go +++ b/relay/billing/ratio/model.go @@ -9,9 +9,10 @@ import ( ) const ( - USD2RMB = 7 - USD = 500 // $0.002 = 1 -> $1 = 500 - RMB = USD / USD2RMB + USD2RMB = 7 + USD = 500 // $0.002 = 1 -> $1 = 500 + MILLI_USD = 1.0 / 1000 * USD + RMB = USD / USD2RMB ) // ModelRatio @@ -81,15 +82,17 @@ var ModelRatio = map[string]float64{ "text-moderation-latest": 0.1, "dall-e-2": 0.02 * USD, // $0.016 - $0.020 / image "dall-e-3": 0.04 * USD, // $0.040 - $0.120 / image - // https://www.anthropic.com/api#pricing + // https://docs.anthropic.com/en/docs/about-claude/models "claude-instant-1.2": 0.8 / 1000 * USD, "claude-2.0": 8.0 / 1000 * USD, "claude-2.1": 8.0 / 1000 * USD, "claude-3-haiku-20240307": 0.25 / 1000 * USD, "claude-3-5-haiku-20241022": 1.0 / 1000 * USD, + "claude-3-5-haiku-latest": 1.0 / 1000 * USD, "claude-3-sonnet-20240229": 3.0 / 1000 * USD, "claude-3-5-sonnet-20240620": 3.0 / 1000 * USD, "claude-3-5-sonnet-20241022": 3.0 / 1000 * USD, + "claude-3-5-sonnet-latest" : 3.0 / 1000 * USD, "claude-3-opus-20240229": 15.0 / 1000 * USD, // https://cloud.baidu.com/doc/WENXINWORKSHOP/s/hlrk4akp7 "ERNIE-4.0-8K": 0.120 * RMB, @@ -109,25 +112,40 @@ var ModelRatio = map[string]float64{ "bge-large-en": 0.002 * RMB, "tao-8k": 0.002 * RMB, // https://ai.google.dev/pricing - "gemini-pro": 1, // $0.00025 / 1k characters -> $0.001 / 1k tokens - "gemini-1.0-pro": 1, - "gemini-1.5-pro": 1, - "gemini-1.5-pro-001": 1, - "gemini-1.5-flash": 1, - "gemini-1.5-flash-001": 1, - "gemini-2.0-flash-exp": 1, - "gemini-2.0-flash-thinking-exp": 1, - "aqa": 1, + "gemini-pro": 1, // $0.00025 / 1k characters -> $0.001 / 1k tokens + "gemini-1.0-pro": 1, + "gemini-1.5-pro": 1, + "gemini-1.5-pro-001": 1, + "gemini-1.5-flash": 1, + "gemini-1.5-flash-001": 1, + "gemini-2.0-flash-exp": 1, + "gemini-2.0-flash-thinking-exp": 1, + "gemini-2.0-flash-thinking-exp-01-21": 1, + "aqa": 1, // https://open.bigmodel.cn/pricing - "glm-4": 0.1 * RMB, - "glm-4v": 0.1 * RMB, - "glm-3-turbo": 0.005 * RMB, - "embedding-2": 0.0005 * RMB, - "chatglm_turbo": 0.3572, // ¥0.005 / 1k tokens - "chatglm_pro": 0.7143, // ¥0.01 / 1k tokens - "chatglm_std": 0.3572, // ¥0.005 / 1k tokens - "chatglm_lite": 0.1429, // ¥0.002 / 1k tokens - "cogview-3": 0.25 * RMB, + "glm-zero-preview": 0.01 * RMB, + "glm-4-plus": 0.05 * RMB, + "glm-4-0520": 0.1 * RMB, + "glm-4-airx": 0.01 * RMB, + "glm-4-air": 0.0005 * RMB, + "glm-4-long": 0.001 * RMB, + "glm-4-flashx": 0.0001 * RMB, + "glm-4-flash": 0, + "glm-4": 0.1 * RMB, // deprecated model, available until 2025/06 + "glm-3-turbo": 0.001 * RMB, // deprecated model, available until 2025/06 + "glm-4v-plus": 0.004 * RMB, + "glm-4v": 0.05 * RMB, + "glm-4v-flash": 0, + "cogview-3-plus": 0.06 * RMB, + "cogview-3": 0.1 * RMB, + "cogview-3-flash": 0, + "cogviewx": 0.5 * RMB, + "cogviewx-flash": 0, + "charglm-4": 0.001 * RMB, + "emohaa": 0.015 * RMB, + "codegeex-4": 0.0001 * RMB, + "embedding-2": 0.0005 * RMB, + "embedding-3": 0.0005 * RMB, // https://help.aliyun.com/zh/dashscope/developer-reference/tongyi-thousand-questions-metering-and-billing "qwen-turbo": 1.4286, // ¥0.02 / 1k tokens "qwen-turbo-latest": 1.4286, @@ -214,9 +232,19 @@ var ModelRatio = map[string]float64{ "embedding-bert-512-v1": 0.0715, // ¥0.001 / 1k tokens "embedding_s1_v1": 0.0715, // ¥0.001 / 1k tokens "semantic_similarity_s1_v1": 0.0715, // ¥0.001 / 1k tokens - "hunyuan": 7.143, // ¥0.1 / 1k tokens // https://cloud.tencent.com/document/product/1729/97731#e0e6be58-60c8-469f-bdeb-6c264ce3b4d0 - "ChatStd": 0.01 * RMB, - "ChatPro": 0.1 * RMB, + // https://cloud.tencent.com/document/product/1729/97731#e0e6be58-60c8-469f-bdeb-6c264ce3b4d0 + "hunyuan-turbo": 0.015 * RMB, + "hunyuan-large": 0.004 * RMB, + "hunyuan-large-longcontext": 0.006 * RMB, + "hunyuan-standard": 0.0008 * RMB, + "hunyuan-standard-256K": 0.0005 * RMB, + "hunyuan-translation-lite": 0.005 * RMB, + "hunyuan-role": 0.004 * RMB, + "hunyuan-functioncall": 0.004 * RMB, + "hunyuan-code": 0.004 * RMB, + "hunyuan-turbo-vision": 0.08 * RMB, + "hunyuan-vision": 0.018 * RMB, + "hunyuan-embedding": 0.0007 * RMB, // https://platform.moonshot.cn/pricing "moonshot-v1-8k": 0.012 * RMB, "moonshot-v1-32k": 0.024 * RMB, @@ -279,8 +307,8 @@ var ModelRatio = map[string]float64{ "command-r": 0.5 / 1000 * USD, "command-r-plus": 3.0 / 1000 * USD, // https://platform.deepseek.com/api-docs/pricing/ - "deepseek-chat": 1.0 / 1000 * RMB, - "deepseek-coder": 1.0 / 1000 * RMB, + "deepseek-chat": 0.14 * MILLI_USD, + "deepseek-reasoner": 0.55 * MILLI_USD, // https://www.deepl.com/pro?cta=header-prices "deepl-zh": 25.0 / 1000 * USD, "deepl-en": 25.0 / 1000 * USD, @@ -337,6 +365,11 @@ var CompletionRatio = map[string]float64{ // aws llama3 "llama3-8b-8192(33)": 0.0006 / 0.0003, "llama3-70b-8192(33)": 0.0035 / 0.00265, + // whisper + "whisper-1": 0, // only count input tokens + // deepseek + "deepseek-chat": 0.28 / 0.14, + "deepseek-reasoner": 2.19 / 0.55, } var ( diff --git a/relay/controller/helper.go b/relay/controller/helper.go index 5f5fc90c..5b6f023f 100644 --- a/relay/controller/helper.go +++ b/relay/controller/helper.go @@ -4,12 +4,15 @@ import ( "context" "errors" "fmt" - "github.com/songquanpeng/one-api/relay/constant/role" "math" "net/http" "strings" + "github.com/songquanpeng/one-api/common/helper" + "github.com/songquanpeng/one-api/relay/constant/role" + "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common" "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/logger" @@ -119,12 +122,20 @@ func postConsumeQuota(ctx context.Context, usage *relaymodel.Usage, meta *meta.M if err != nil { logger.Error(ctx, "error update user quota cache: "+err.Error()) } - var extraLog string - if systemPromptReset { - extraLog = " (注意系统提示词已被重置)" - } - logContent := fmt.Sprintf("模型倍率 %.2f,分组倍率 %.2f,补全倍率 %.2f%s", modelRatio, groupRatio, completionRatio, extraLog) - model.RecordConsumeLog(ctx, meta.UserId, meta.ChannelId, promptTokens, completionTokens, textRequest.Model, meta.TokenName, quota, logContent) + logContent := fmt.Sprintf("倍率:%.2f × %.2f × %.2f", modelRatio, groupRatio, completionRatio) + model.RecordConsumeLog(ctx, &model.Log{ + UserId: meta.UserId, + ChannelId: meta.ChannelId, + PromptTokens: promptTokens, + CompletionTokens: completionTokens, + ModelName: textRequest.Model, + TokenName: meta.TokenName, + Quota: int(quota), + Content: logContent, + IsStream: meta.IsStream, + ElapsedTime: helper.CalcElapsedTime(meta.StartTime), + SystemPromptReset: systemPromptReset, + }) model.UpdateUserUsedQuotaAndRequestCount(meta.UserId, quota) model.UpdateChannelUsedQuota(meta.ChannelId, quota) } diff --git a/relay/controller/image.go b/relay/controller/image.go index 1b69d97d..9a980a14 100644 --- a/relay/controller/image.go +++ b/relay/controller/image.go @@ -10,6 +10,7 @@ import ( "net/http" "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common" "github.com/songquanpeng/one-api/common/ctxkey" "github.com/songquanpeng/one-api/common/logger" @@ -209,8 +210,17 @@ func RelayImageHelper(c *gin.Context, relayMode int) *relaymodel.ErrorWithStatus } if quota != 0 { tokenName := c.GetString(ctxkey.TokenName) - logContent := fmt.Sprintf("模型倍率 %.2f,分组倍率 %.2f", modelRatio, groupRatio) - model.RecordConsumeLog(ctx, meta.UserId, meta.ChannelId, 0, 0, imageRequest.Model, tokenName, quota, logContent) + logContent := fmt.Sprintf("倍率:%.2f × %.2f", modelRatio, groupRatio) + model.RecordConsumeLog(ctx, &model.Log{ + UserId: meta.UserId, + ChannelId: meta.ChannelId, + PromptTokens: 0, + CompletionTokens: 0, + ModelName: imageRequest.Model, + TokenName: tokenName, + Quota: int(quota), + Content: logContent, + }) model.UpdateUserUsedQuotaAndRequestCount(meta.UserId, quota) channelId := c.GetInt(ctxkey.ChannelId) model.UpdateChannelUsedQuota(channelId, quota) diff --git a/relay/controller/text.go b/relay/controller/text.go index 9e645635..1b150227 100644 --- a/relay/controller/text.go +++ b/relay/controller/text.go @@ -4,11 +4,12 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/songquanpeng/one-api/common/config" "io" "net/http" "github.com/gin-gonic/gin" + + "github.com/songquanpeng/one-api/common/config" "github.com/songquanpeng/one-api/common/logger" "github.com/songquanpeng/one-api/relay" "github.com/songquanpeng/one-api/relay/adaptor" diff --git a/relay/meta/relay_meta.go b/relay/meta/relay_meta.go index b33a2f99..842edae3 100644 --- a/relay/meta/relay_meta.go +++ b/relay/meta/relay_meta.go @@ -1,12 +1,15 @@ package meta import ( + "strings" + "time" + "github.com/gin-gonic/gin" + "github.com/songquanpeng/one-api/common/ctxkey" "github.com/songquanpeng/one-api/model" "github.com/songquanpeng/one-api/relay/channeltype" "github.com/songquanpeng/one-api/relay/relaymode" - "strings" ) type Meta struct { @@ -32,6 +35,7 @@ type Meta struct { PromptTokens int // only for DoResponse SystemPrompt string Cache bool + StartTime time.Time } func GetByContext(c *gin.Context) *Meta { @@ -49,6 +53,7 @@ func GetByContext(c *gin.Context) *Meta { APIKey: strings.TrimPrefix(c.Request.Header.Get("Authorization"), "Bearer "), RequestURLPath: c.Request.URL.String(), SystemPrompt: c.GetString(ctxkey.SystemPrompt), + StartTime: time.Now(), } cfg, ok := c.Get(ctxkey.Config) if ok { diff --git a/web/air/src/components/LogsTable.js b/web/air/src/components/LogsTable.js index 004188c3..7d372d49 100644 --- a/web/air/src/components/LogsTable.js +++ b/web/air/src/components/LogsTable.js @@ -28,6 +28,8 @@ function renderType(type) { return 管理 ; case 4: return 系统 ; + case 5: + return 测试 ; default: return 未知 ; } diff --git a/web/air/src/constants/channel.constants.js b/web/air/src/constants/channel.constants.js index e7b25399..68ca987a 100644 --- a/web/air/src/constants/channel.constants.js +++ b/web/air/src/constants/channel.constants.js @@ -7,7 +7,7 @@ export const CHANNEL_OPTIONS = [ { key: 24, text: 'Google Gemini', value: 24, color: 'orange' }, { key: 28, text: 'Mistral AI', value: 28, color: 'orange' }, { key: 41, text: 'Novita', value: 41, color: 'purple' }, - { key: 40, text: '字节跳动豆包', value: 40, color: 'blue' }, + {key: 40, text: '火山引擎', value: 40, color: 'blue'}, { key: 15, text: '百度文心千帆', value: 15, color: 'blue' }, { key: 17, text: '阿里通义千问', value: 17, color: 'orange' }, { key: 18, text: '讯飞星火认知', value: 18, color: 'blue' }, diff --git a/web/berry/src/constants/ChannelConstants.js b/web/berry/src/constants/ChannelConstants.js index 375adcd9..4c188d87 100644 --- a/web/berry/src/constants/ChannelConstants.js +++ b/web/berry/src/constants/ChannelConstants.js @@ -49,7 +49,7 @@ export const CHANNEL_OPTIONS = { }, 40: { key: 40, - text: '字节跳动豆包', + text: '火山引擎', value: 40, color: 'primary' }, diff --git a/web/berry/src/utils/common.js b/web/berry/src/utils/common.js index bd85f8bf..be296122 100644 --- a/web/berry/src/utils/common.js +++ b/web/berry/src/utils/common.js @@ -1,247 +1,260 @@ -import { enqueueSnackbar } from 'notistack'; -import { snackbarConstants } from 'constants/SnackbarConstants'; -import { API } from './api'; +import {enqueueSnackbar} from 'notistack'; +import {snackbarConstants} from 'constants/SnackbarConstants'; +import {API} from './api'; export function getSystemName() { - let system_name = localStorage.getItem('system_name'); - if (!system_name) return 'One API'; - return system_name; + let system_name = localStorage.getItem('system_name'); + if (!system_name) return 'One API'; + return system_name; } export function isMobile() { - return window.innerWidth <= 600; + return window.innerWidth <= 600; } // eslint-disable-next-line -export function SnackbarHTMLContent({ htmlContent }) { - return
; +export function SnackbarHTMLContent({htmlContent}) { + return
; } export function getSnackbarOptions(variant) { - let options = snackbarConstants.Common[variant]; - if (isMobile()) { - // 合并 options 和 snackbarConstants.Mobile - options = { ...options, ...snackbarConstants.Mobile }; - } - return options; + let options = snackbarConstants.Common[variant]; + if (isMobile()) { + // 合并 options 和 snackbarConstants.Mobile + options = {...options, ...snackbarConstants.Mobile}; + } + return options; } export function showError(error) { - if (error.message) { - if (error.name === 'AxiosError') { - switch (error.response.status) { - case 429: - enqueueSnackbar('错误:请求次数过多,请稍后再试!', getSnackbarOptions('ERROR')); - break; - case 500: - enqueueSnackbar('错误:服务器内部错误,请联系管理员!', getSnackbarOptions('ERROR')); - break; - case 405: - enqueueSnackbar('本站仅作演示之用,无服务端!', getSnackbarOptions('INFO')); - break; - default: - enqueueSnackbar('错误:' + error.message, getSnackbarOptions('ERROR')); - } - return; + if (error.message) { + if (error.name === 'AxiosError') { + switch (error.response.status) { + case 429: + enqueueSnackbar('错误:请求次数过多,请稍后再试!', getSnackbarOptions('ERROR')); + break; + case 500: + enqueueSnackbar('错误:服务器内部错误,请联系管理员!', getSnackbarOptions('ERROR')); + break; + case 405: + enqueueSnackbar('本站仅作演示之用,无服务端!', getSnackbarOptions('INFO')); + break; + default: + enqueueSnackbar('错误:' + error.message, getSnackbarOptions('ERROR')); + } + return; + } + } else { + enqueueSnackbar('错误:' + error, getSnackbarOptions('ERROR')); } - } else { - enqueueSnackbar('错误:' + error, getSnackbarOptions('ERROR')); - } } export function showNotice(message, isHTML = false) { - if (isHTML) { - enqueueSnackbar(, getSnackbarOptions('NOTICE')); - } else { - enqueueSnackbar(message, getSnackbarOptions('NOTICE')); - } + if (isHTML) { + enqueueSnackbar(, getSnackbarOptions('NOTICE')); + } else { + enqueueSnackbar(message, getSnackbarOptions('NOTICE')); + } } export function showWarning(message) { - enqueueSnackbar(message, getSnackbarOptions('WARNING')); + enqueueSnackbar(message, getSnackbarOptions('WARNING')); } export function showSuccess(message) { - enqueueSnackbar(message, getSnackbarOptions('SUCCESS')); + enqueueSnackbar(message, getSnackbarOptions('SUCCESS')); } export function showInfo(message) { - enqueueSnackbar(message, getSnackbarOptions('INFO')); + enqueueSnackbar(message, getSnackbarOptions('INFO')); } export async function getOAuthState() { - const res = await API.get('/api/oauth/state'); - const { success, message, data } = res.data; - if (success) { - return data; - } else { - showError(message); - return ''; - } + const res = await API.get('/api/oauth/state'); + const {success, message, data} = res.data; + if (success) { + return data; + } else { + showError(message); + return ''; + } } export async function onGitHubOAuthClicked(github_client_id, openInNewTab = false) { - const state = await getOAuthState(); - if (!state) return; - let url = `https://github.com/login/oauth/authorize?client_id=${github_client_id}&state=${state}&scope=user:email`; - if (openInNewTab) { - window.open(url); - } else { - window.location.href = url; - } + const state = await getOAuthState(); + if (!state) return; + let url = `https://github.com/login/oauth/authorize?client_id=${github_client_id}&state=${state}&scope=user:email`; + if (openInNewTab) { + window.open(url); + } else { + window.location.href = url; + } } export async function onLarkOAuthClicked(lark_client_id) { - const state = await getOAuthState(); - if (!state) return; - let redirect_uri = `${window.location.origin}/oauth/lark`; - window.open(`https://accounts.feishu.cn/open-apis/authen/v1/authorize?redirect_uri=${redirect_uri}&client_id=${lark_client_id}&state=${state}`); + const state = await getOAuthState(); + if (!state) return; + let redirect_uri = `${window.location.origin}/oauth/lark`; + window.open(`https://accounts.feishu.cn/open-apis/authen/v1/authorize?redirect_uri=${redirect_uri}&client_id=${lark_client_id}&state=${state}`); } export async function onOidcClicked(auth_url, client_id, openInNewTab = false) { - const state = await getOAuthState(); - if (!state) return; - const redirect_uri = `${window.location.origin}/oauth/oidc`; - const response_type = "code"; - const scope = "openid profile email"; - const url = `${auth_url}?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=${response_type}&scope=${scope}&state=${state}`; - if (openInNewTab) { - window.open(url); - } else - { - window.location.href = url; - } + const state = await getOAuthState(); + if (!state) return; + const redirect_uri = `${window.location.origin}/oauth/oidc`; + const response_type = "code"; + const scope = "openid profile email"; + const url = `${auth_url}?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=${response_type}&scope=${scope}&state=${state}`; + if (openInNewTab) { + window.open(url); + } else { + window.location.href = url; + } } export function isAdmin() { - let user = localStorage.getItem('user'); - if (!user) return false; - user = JSON.parse(user); - return user.role >= 10; + let user = localStorage.getItem('user'); + if (!user) return false; + user = JSON.parse(user); + return user.role >= 10; } export function timestamp2string(timestamp) { - let date = new Date(timestamp * 1000); - let year = date.getFullYear().toString(); - let month = (date.getMonth() + 1).toString(); - let day = date.getDate().toString(); - let hour = date.getHours().toString(); - let minute = date.getMinutes().toString(); - let second = date.getSeconds().toString(); - if (month.length === 1) { - month = '0' + month; - } - if (day.length === 1) { - day = '0' + day; - } - if (hour.length === 1) { - hour = '0' + hour; - } - if (minute.length === 1) { - minute = '0' + minute; - } - if (second.length === 1) { - second = '0' + second; - } - return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; + let date = new Date(timestamp * 1000); + let year = date.getFullYear().toString(); + let month = (date.getMonth() + 1).toString(); + let day = date.getDate().toString(); + let hour = date.getHours().toString(); + let minute = date.getMinutes().toString(); + let second = date.getSeconds().toString(); + if (month.length === 1) { + month = '0' + month; + } + if (day.length === 1) { + day = '0' + day; + } + if (hour.length === 1) { + hour = '0' + hour; + } + if (minute.length === 1) { + minute = '0' + minute; + } + if (second.length === 1) { + second = '0' + second; + } + return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second; } export function calculateQuota(quota, digits = 2) { - let quotaPerUnit = localStorage.getItem('quota_per_unit'); - quotaPerUnit = parseFloat(quotaPerUnit); + let quotaPerUnit = localStorage.getItem('quota_per_unit'); + quotaPerUnit = parseFloat(quotaPerUnit); - return (quota / quotaPerUnit).toFixed(digits); + return (quota / quotaPerUnit).toFixed(digits); } export function renderQuota(quota, digits = 2) { - let displayInCurrency = localStorage.getItem('display_in_currency'); - displayInCurrency = displayInCurrency === 'true'; - if (displayInCurrency) { - return '$' + calculateQuota(quota, digits); - } - return renderNumber(quota); + let displayInCurrency = localStorage.getItem('display_in_currency'); + displayInCurrency = displayInCurrency === 'true'; + if (displayInCurrency) { + return '$' + calculateQuota(quota, digits); + } + return renderNumber(quota); } export const verifyJSON = (str) => { - try { - JSON.parse(str); - } catch (e) { - return false; - } - return true; + try { + JSON.parse(str); + } catch (e) { + return false; + } + return true; }; export function renderNumber(num) { - if (num >= 1000000000) { - return (num / 1000000000).toFixed(1) + 'B'; - } else if (num >= 1000000) { - return (num / 1000000).toFixed(1) + 'M'; - } else if (num >= 10000) { - return (num / 1000).toFixed(1) + 'k'; - } else { - return num; - } + if (num >= 1000000000) { + return (num / 1000000000).toFixed(1) + 'B'; + } else if (num >= 1000000) { + return (num / 1000000).toFixed(1) + 'M'; + } else if (num >= 10000) { + return (num / 1000).toFixed(1) + 'k'; + } else { + return num; + } } export function renderQuotaWithPrompt(quota, digits) { - let displayInCurrency = localStorage.getItem('display_in_currency'); - displayInCurrency = displayInCurrency === 'true'; - if (displayInCurrency) { - return `(等价金额:${renderQuota(quota, digits)})`; - } - return ''; + let displayInCurrency = localStorage.getItem('display_in_currency'); + displayInCurrency = displayInCurrency === 'true'; + if (displayInCurrency) { + return `(等价金额:${renderQuota(quota, digits)})`; + } + return ''; } export function downloadTextAsFile(text, filename) { - let blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); - let url = URL.createObjectURL(blob); - let a = document.createElement('a'); - a.href = url; - a.download = filename; - a.click(); + let blob = new Blob([text], {type: 'text/plain;charset=utf-8'}); + let url = URL.createObjectURL(blob); + let a = document.createElement('a'); + a.href = url; + a.download = filename; + a.click(); } export function removeTrailingSlash(url) { - if (url.endsWith('/')) { - return url.slice(0, -1); - } else { - return url; - } + if (url.endsWith('/')) { + return url.slice(0, -1); + } else { + return url; + } } let channelModels = undefined; + export async function loadChannelModels() { - const res = await API.get('/api/models'); - const { success, data } = res.data; - if (!success) { - return; - } - channelModels = data; - localStorage.setItem('channel_models', JSON.stringify(data)); + const res = await API.get('/api/models'); + const {success, data} = res.data; + if (!success) { + return; + } + channelModels = data; + localStorage.setItem('channel_models', JSON.stringify(data)); } export function getChannelModels(type) { - if (channelModels !== undefined && type in channelModels) { - return channelModels[type]; - } - let models = localStorage.getItem('channel_models'); - if (!models) { + if (channelModels !== undefined && type in channelModels) { + return channelModels[type]; + } + let models = localStorage.getItem('channel_models'); + if (!models) { + return []; + } + channelModels = JSON.parse(models); + if (type in channelModels) { + return channelModels[type]; + } return []; - } - channelModels = JSON.parse(models); - if (type in channelModels) { - return channelModels[type]; - } - return []; } export function copy(text, name = '') { - try { - navigator.clipboard.writeText(text); - } catch (error) { - text = `复制${name}失败,请手动复制:

${text}`; - enqueueSnackbar(, getSnackbarOptions('COPY')); - return; - } - showSuccess(`复制${name}成功!`); + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(text).then(() => { + showNotice(`复制${name}成功!`, true); + }, () => { + text = `复制${name}失败,请手动复制:

${text}`; + enqueueSnackbar(, getSnackbarOptions('COPY')); + }); + } else { + const textArea = document.createElement("textarea"); + textArea.value = text; + document.body.appendChild(textArea); + textArea.select(); + try { + document.execCommand('copy'); + showNotice(`复制${name}成功!`, true); + } catch (err) { + text = `复制${name}失败,请手动复制:

${text}`; + enqueueSnackbar(, getSnackbarOptions('COPY')); + } + document.body.removeChild(textArea); + } } diff --git a/web/berry/src/views/Log/type/LogType.js b/web/berry/src/views/Log/type/LogType.js index 4891b66b..23db2766 100644 --- a/web/berry/src/views/Log/type/LogType.js +++ b/web/berry/src/views/Log/type/LogType.js @@ -3,7 +3,8 @@ const LOG_TYPE = { 1: { value: '1', text: '充值', color: 'primary' }, 2: { value: '2', text: '消费', color: 'orange' }, 3: { value: '3', text: '管理', color: 'default' }, - 4: { value: '4', text: '系统', color: 'secondary' } + 4: { value: '4', text: '系统', color: 'secondary' }, + 5: { value: '5', text: '测试', color: 'secondary' }, }; export default LOG_TYPE; diff --git a/web/default/package.json b/web/default/package.json index ba45011f..350517b3 100644 --- a/web/default/package.json +++ b/web/default/package.json @@ -5,14 +5,19 @@ "dependencies": { "axios": "^0.27.2", "history": "^5.3.0", + "i18next": "^24.2.2", + "i18next-browser-languagedetector": "^8.0.2", "marked": "^4.1.1", + "moment": "^2.30.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-dropzone": "^14.2.3", + "react-i18next": "^15.4.0", "react-router-dom": "^6.3.0", "react-scripts": "5.0.1", "react-toastify": "^9.0.8", "react-turnstile": "^1.0.5", + "recharts": "^2.15.1", "semantic-ui-css": "^2.5.0", "semantic-ui-react": "^2.1.3" }, diff --git a/web/default/src/App.js b/web/default/src/App.js index 4ece4eeb..e76ee7ea 100644 --- a/web/default/src/App.js +++ b/web/default/src/App.js @@ -25,6 +25,7 @@ import TopUp from './pages/TopUp'; import Log from './pages/Log'; import Chat from './pages/Chat'; import LarkOAuth from './components/LarkOAuth'; +import Dashboard from './pages/Dashboard'; const Home = lazy(() => import('./pages/Home')); const About = lazy(() => import('./pages/About')); @@ -41,32 +42,37 @@ function App() { } }; const loadStatus = async () => { - const res = await API.get('/api/status'); - const { success, data } = res.data; - if (success) { - localStorage.setItem('status', JSON.stringify(data)); - statusDispatch({ type: 'set', payload: data }); - localStorage.setItem('system_name', data.system_name); - localStorage.setItem('logo', data.logo); - localStorage.setItem('footer_html', data.footer_html); - localStorage.setItem('quota_per_unit', data.quota_per_unit); - localStorage.setItem('display_in_currency', data.display_in_currency); - if (data.chat_link) { - localStorage.setItem('chat_link', data.chat_link); + try { + const res = await API.get('/api/status'); + const { success, message, data } = res.data || {}; // Add default empty object + if (success && data) { + // Check data exists + localStorage.setItem('status', JSON.stringify(data)); + statusDispatch({ type: 'set', payload: data }); + localStorage.setItem('system_name', data.system_name); + localStorage.setItem('logo', data.logo); + localStorage.setItem('footer_html', data.footer_html); + localStorage.setItem('quota_per_unit', data.quota_per_unit); + localStorage.setItem('display_in_currency', data.display_in_currency); + if (data.chat_link) { + localStorage.setItem('chat_link', data.chat_link); + } else { + localStorage.removeItem('chat_link'); + } + if ( + data.version !== process.env.REACT_APP_VERSION && + data.version !== 'v0.0.0' && + process.env.REACT_APP_VERSION !== '' + ) { + showNotice( + `新版本可用:${data.version},请使用快捷键 Shift + F5 刷新页面` + ); + } } else { - localStorage.removeItem('chat_link'); + showError(message || '无法正常连接至服务器!'); } - if ( - data.version !== process.env.REACT_APP_VERSION && - data.version !== 'v0.0.0' && - process.env.REACT_APP_VERSION !== '' - ) { - showNotice( - `新版本可用:${data.version},请使用快捷键 Shift + F5 刷新页面` - ); - } - } else { - showError('无法正常连接至服务器!'); + } catch (error) { + showError(error.message || '无法正常连接至服务器!'); } }; @@ -261,11 +267,11 @@ function App() { - }> - - - + + }> + + + } /> } /> - - } /> + + + + } + /> + } /> ); } diff --git a/web/default/src/components/ChannelsTable.js b/web/default/src/components/ChannelsTable.js index e745814b..e9ac31a0 100644 --- a/web/default/src/components/ChannelsTable.js +++ b/web/default/src/components/ChannelsTable.js @@ -1,5 +1,16 @@ import React, { useEffect, useState } from 'react'; -import { Button, Dropdown, Form, Input, Label, Message, Pagination, Popup, Table } from 'semantic-ui-react'; +import { useTranslation } from 'react-i18next'; +import { + Button, + Dropdown, + Form, + Input, + Label, + Message, + Pagination, + Popup, + Table, +} from 'semantic-ui-react'; import { Link } from 'react-router-dom'; import { API, @@ -9,34 +20,38 @@ import { showError, showInfo, showSuccess, - timestamp2string + timestamp2string, } from '../helpers'; import { CHANNEL_OPTIONS, ITEMS_PER_PAGE } from '../constants'; import { renderGroup, renderNumber } from '../helpers/render'; function renderTimestamp(timestamp) { - return ( - <> - {timestamp2string(timestamp)} - - ); + return <>{timestamp2string(timestamp)}; } let type2label = undefined; -function renderType(type) { +function renderType(type, t) { if (!type2label) { - type2label = new Map; + type2label = new Map(); for (let i = 0; i < CHANNEL_OPTIONS.length; i++) { type2label[CHANNEL_OPTIONS[i].value] = CHANNEL_OPTIONS[i]; } - type2label[0] = { value: 0, text: '未知类型', color: 'grey' }; + type2label[0] = { + value: 0, + text: t('channel.table.status_unknown'), + color: 'grey', + }; } - return ; + return ( + + ); } -function renderBalance(type, balance) { +function renderBalance(type, balance, t) { switch (type) { case 1: // OpenAI return ${balance.toFixed(2)}; @@ -57,17 +72,18 @@ function renderBalance(type, balance) { case 44: // SiliconFlow return ¥{balance.toFixed(2)}; default: - return 不支持; + return {t('channel.table.balance_not_supported')}; } } function isShowDetail() { - return localStorage.getItem("show_detail") === "true"; + return localStorage.getItem('show_detail') === 'true'; } -const promptID = "detail" +const promptID = 'detail'; const ChannelsTable = () => { + const { t } = useTranslation(); const [channels, setChannels] = useState([]); const [loading, setLoading] = useState(true); const [activePage, setActivePage] = useState(1); @@ -81,33 +97,37 @@ const ChannelsTable = () => { const res = await API.get(`/api/channel/?p=${startIdx}`); const { success, message, data } = res.data; if (success) { - let localChannels = data.map((channel) => { - if (channel.models === '') { - channel.models = []; - channel.test_model = ""; - } else { - channel.models = channel.models.split(','); - if (channel.models.length > 0) { - channel.test_model = channel.models[0]; - } - channel.model_options = channel.models.map((model) => { - return { - key: model, - text: model, - value: model, - } - }) - console.log('channel', channel) - } - return channel; - }); - if (startIdx === 0) { - setChannels(localChannels); + let localChannels = data.map((channel) => { + if (channel.models === '') { + channel.models = []; + channel.test_model = ''; } else { - let newChannels = [...channels]; - newChannels.splice(startIdx * ITEMS_PER_PAGE, data.length, ...localChannels); - setChannels(newChannels); + channel.models = channel.models.split(','); + if (channel.models.length > 0) { + channel.test_model = channel.models[0]; + } + channel.model_options = channel.models.map((model) => { + return { + key: model, + text: model, + value: model, + }; + }); + console.log('channel', channel); } + return channel; + }); + if (startIdx === 0) { + setChannels(localChannels); + } else { + let newChannels = [...channels]; + newChannels.splice( + startIdx * ITEMS_PER_PAGE, + data.length, + ...localChannels + ); + setChannels(newChannels); + } } else { showError(message); } @@ -131,8 +151,8 @@ const ChannelsTable = () => { const toggleShowDetail = () => { setShowDetail(!showDetail); - localStorage.setItem("show_detail", (!showDetail).toString()); - } + localStorage.setItem('show_detail', (!showDetail).toString()); + }; useEffect(() => { loadChannels(0) @@ -178,7 +198,7 @@ const ChannelsTable = () => { } const { success, message } = res.data; if (success) { - showSuccess('操作成功完成!'); + showSuccess(t('channel.messages.operation_success')); let channel = res.data.data; let newChannels = [...channels]; let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx; @@ -193,52 +213,80 @@ const ChannelsTable = () => { } }; - const renderStatus = (status) => { + const renderStatus = (status, t) => { switch (status) { case 1: - return ; + return ( + + ); case 2: return ( - 已禁用 - } - content='本渠道被手动禁用' + trigger={ + + } + content={t('channel.table.status_disabled_tip')} basic /> ); case 3: return ( - 已禁用 - } - content='本渠道被程序自动禁用' + trigger={ + + } + content={t('channel.table.status_auto_disabled_tip')} basic /> ); default: return ( ); } }; - const renderResponseTime = (responseTime) => { + const renderResponseTime = (responseTime, t) => { let time = responseTime / 1000; - time = time.toFixed(2) + ' 秒'; + time = time.toFixed(2) + 's'; if (responseTime === 0) { - return ; + return ( + + ); } else if (responseTime <= 1000) { - return ; + return ( + + ); } else if (responseTime <= 3000) { - return ; + return ( + + ); } else if (responseTime <= 5000) { - return ; + return ( + + ); } else { - return ; + return ( + + ); } }; @@ -277,7 +325,9 @@ const ChannelsTable = () => { newChannels[realIdx].response_time = time * 1000; newChannels[realIdx].test_time = Date.now() / 1000; setChannels(newChannels); - showInfo(`渠道 ${name} 测试成功,模型 ${model},耗时 ${time.toFixed(2)} 秒。`); + showSuccess( + t('channel.messages.test_success', { name, model, time, message }) + ); } else { showError(message); } @@ -292,7 +342,7 @@ const ChannelsTable = () => { const res = await API.get(`/api/channel/test?scope=${scope}`); const { success, message } = res.data; if (success) { - showInfo('已成功开始测试渠道,请刷新页面查看结果。'); + showInfo(t('channel.messages.test_all_started')); } else { showError(message); } @@ -302,7 +352,9 @@ const ChannelsTable = () => { const res = await API.delete(`/api/channel/disabled`); const { success, message, data } = res.data; if (success) { - showSuccess(`已删除所有禁用渠道,共计 ${data} 个`); + showSuccess( + t('channel.messages.delete_disabled_success', { count: data }) + ); await refresh(); } else { showError(message); @@ -318,7 +370,7 @@ const ChannelsTable = () => { newChannels[realIdx].balance = balance; newChannels[realIdx].balance_updated_time = Date.now() / 1000; setChannels(newChannels); - showInfo(`渠道 ${name} 余额更新成功!`); + showSuccess(t('channel.messages.balance_update_success', { name })); } else { showError(message); } @@ -329,7 +381,7 @@ const ChannelsTable = () => { const res = await API.get(`/api/channel/update_balance`); const { success, message } = res.data; if (success) { - showInfo('已更新完毕所有已启用渠道余额!'); + showInfo(t('channel.messages.all_balance_updated')); } else { showError(message); } @@ -360,7 +412,6 @@ const ChannelsTable = () => { setLoading(false); }; - return ( <>
@@ -368,27 +419,27 @@ const ChannelsTable = () => { icon='search' fluid iconPosition='left' - placeholder='搜索渠道的 ID,名称和密钥 ...' + placeholder={t('channel.search')} value={searchKeyword} loading={searching} onChange={handleKeywordChange} />
- { - showPrompt && ( - { + {showPrompt && ( + { setShowPrompt(false); setPromptShown(promptID); - }}> - OpenAI 渠道已经不再支持通过 key 获取余额,因此余额显示为 0。对于支持的渠道类型,请点击余额进行刷新。 -
- 渠道测试仅支持 chat 模型,优先使用 gpt-3.5-turbo,如果该模型不可用则使用你所配置的模型列表中的第一个模型。 -
- 点击下方详情按钮可以显示余额以及设置额外的测试模型。 -
- ) - } - + }} + > + {t('channel.balance_notice')} +
+ {t('channel.test_notice')} +
+ {t('channel.detail_notice')} + + )} +
{ sortChannel('id'); }} > - ID + {t('channel.table.id')} { sortChannel('name'); }} > - 名称 + {t('channel.table.name')} { sortChannel('group'); }} > - 分组 + {t('channel.table.group')} { sortChannel('type'); }} > - 类型 + {t('channel.table.type')} { sortChannel('status'); }} > - 状态 + {t('channel.table.status')} { sortChannel('response_time'); }} > - 响应时间 + {t('channel.table.response_time')} { }} hidden={!showDetail} > - 余额 + {t('channel.table.balance')} { sortChannel('priority'); }} > - 优先级 + {t('channel.table.priority')} - - 操作 + + {t('channel.table.actions')} @@ -472,48 +525,65 @@ const ChannelsTable = () => { return ( {channel.id} - {channel.name ? channel.name : '无'} + + {channel.name ? channel.name : t('channel.table.no_name')} + {renderGroup(channel.group)} - {renderType(channel.type)} - {renderStatus(channel.status)} + {renderType(channel.type, t)} + {renderStatus(channel.status, t)} { - manageChannel( - channel.id, - 'priority', - idx, - event.target.value - ); - }}> - - } - content='渠道选择优先级,越高越优先' + trigger={ + { + manageChannel( + channel.id, + 'priority', + idx, + event.target.value + ); + }} + > + + + } + content={t('channel.table.priority_tip')} basic />
- - - { - sortLog('created_time'); - }} +
+ {t('log.usage_details')}({t('log.total_quota')}: + {showStat && renderQuota(stat.quota, t)} + {!showStat && ( + + {t('log.click_to_view')} + + )} + ) +
+
+ + + + + + + {t('log.buttons.submit')} + + + {isAdminUser && ( + <> + + + + + + )} + setSearchKeyword(value)} + /> + +
+ + + { + sortLog('created_time'); + }} + width={3} + > + {t('log.table.time')} + + {isAdminUser && ( + { + sortLog('channel'); + }} + width={1} > - 时间 + {t('log.table.channel')} - { - isAdminUser && { + sortLog('type'); + }} + width={1} + > + {t('log.table.type')} + + { + sortLog('model_name'); + }} + width={2} + > + {t('log.table.model')} + + {showUserTokenQuota() && ( + <> + {isAdminUser && ( + { + sortLog('username'); + }} + width={2} + > + {t('log.table.username')} + + )} + { - sortLog('channel'); + sortLog('token_name'); + }} + width={2} + > + {t('log.table.token_name')} + + { + sortLog('prompt_tokens'); }} width={1} > - 渠道 + {t('log.table.prompt_tokens')} - } - { - isAdminUser && { - sortLog('username'); + sortLog('completion_tokens'); }} width={1} > - 用户 + {t('log.table.completion_tokens')} - } - { - sortLog('token_name'); - }} - width={1} - > - 令牌 - - { - sortLog('type'); - }} - width={1} - > - 类型 - - { - sortLog('model_name'); - }} - width={2} - > - 模型 - - { - sortLog('prompt_tokens'); - }} - width={1} - > - 提示 - - { - sortLog('completion_tokens'); - }} - width={1} - > - 补全 - - { - sortLog('quota'); - }} - width={1} - > - 额度 - - { - sortLog('content'); - }} - width={isAdminUser ? 4 : 6} - > - 详情 - - - - - - {logs - .slice( - (activePage - 1) * ITEMS_PER_PAGE, - activePage * ITEMS_PER_PAGE - ) - .map((log, idx) => { - if (log.deleted) return <>; - return ( - - {renderTimestamp(log.created_at)} - { - isAdminUser && ( - {log.channel ? : ''} - ) - } - { - isAdminUser && ( - {log.username ? : ''} - ) - } - {log.token_name ? : ''} - {renderType(log.type)} - {log.model_name ? : ''} - {log.prompt_tokens ? log.prompt_tokens : ''} - {log.completion_tokens ? log.completion_tokens : ''} - {log.quota ? renderQuota(log.quota, 6) : ''} - {log.content} - - ); - })} - - - - - -
- + width={1} + > + {t('log.table.quota')} + + + )} + {t('log.table.detail')} + + + + + {logs + .slice( + (activePage - 1) * ITEMS_PER_PAGE, + activePage * ITEMS_PER_PAGE + ) + .map((log, idx) => { + if (log.deleted) return <>; + return ( + + + {renderTimestamp(log.created_at, log.request_id)} + + {isAdminUser && ( + + {log.channel ? ( + + ) : ( + '' + )} + + )} + {renderType(log.type)} + + {log.model_name ? renderColorLabel(log.model_name) : ''} + + {showUserTokenQuota() && ( + <> + {isAdminUser && ( + + {log.username ? ( + + ) : ( + '' + )} + + )} + + {log.token_name ? renderColorLabel(log.token_name) : ''} + + + + {log.prompt_tokens ? log.prompt_tokens : ''} + + + {log.completion_tokens ? log.completion_tokens : ''} + + + {log.quota ? renderQuota(log.quota, t, 6) : ''} + + + )} + + {renderDetail(log)} + + ); + })} + + + + + + 填入 + } - placeholder='输入自定义模型名称' + placeholder={t('channel.edit.buttons.custom_placeholder')} value={customModel} onChange={(e, { value }) => { setCustomModel(value); @@ -423,43 +486,48 @@ const EditChannel = () => { }} />
- ) - } - { - inputs.type !== 43 && (<> - - - - - - + )} + {inputs.type !== 43 && ( + <> + + + + + + - ) - } - { - inputs.type === 33 && ( + )} + {inputs.type === 33 && ( { label='AK' name='ak' required - placeholder={'AWS IAM Access Key'} + placeholder={t('channel.edit.aws_ak_placeholder')} onChange={handleConfigChange} value={config.ak} autoComplete='' @@ -477,141 +545,152 @@ const EditChannel = () => { label='SK' name='sk' required - placeholder={'AWS IAM Secret Key'} + placeholder={t('channel.edit.aws_sk_placeholder')} onChange={handleConfigChange} value={config.sk} autoComplete='' /> - ) - } - { - inputs.type === 42 && ( + )} + {inputs.type === 42 && ( - ) - } - { - inputs.type === 34 && ( + )} + {inputs.type === 34 && ( ) - } - { - inputs.type !== 33 && inputs.type !== 42 && (batch ? - - : - - ) - } - { - inputs.type === 37 && ( + )} + {inputs.type !== 33 && + inputs.type !== 42 && + (batch ? ( + + + + ) : ( + + + + ))} + {inputs.type === 37 && ( - ) - } - { - inputs.type !== 33 && !isEdit && ( + )} + {inputs.type !== 33 && !isEdit && ( setBatch(!batch)} /> - ) - } - { - inputs.type !== 3 && inputs.type !== 33 && inputs.type !== 8 && inputs.type !== 22 && ( - - - - ) - } - { - inputs.type === 22 && ( + )} + {inputs.type !== 3 && + inputs.type !== 33 && + inputs.type !== 8 && + inputs.type !== 22 && ( + + + + )} + {inputs.type === 22 && ( - ) - } - - - - - + )} + + + + + +
); }; diff --git a/web/default/src/pages/Channel/index.js b/web/default/src/pages/Channel/index.js index edf668b3..97c417d8 100644 --- a/web/default/src/pages/Channel/index.js +++ b/web/default/src/pages/Channel/index.js @@ -1,14 +1,21 @@ import React from 'react'; -import { Header, Segment } from 'semantic-ui-react'; +import { Card } from 'semantic-ui-react'; import ChannelsTable from '../../components/ChannelsTable'; +import { useTranslation } from 'react-i18next'; -const Channel = () => ( - <> - -
管理渠道
- -
- -); +const Channel = () => { + const { t } = useTranslation(); + + return ( +
+ + + {t('channel.title')} + + + +
+ ); +}; export default Channel; diff --git a/web/default/src/pages/Dashboard/Dashboard.css b/web/default/src/pages/Dashboard/Dashboard.css new file mode 100644 index 00000000..ed01b96e --- /dev/null +++ b/web/default/src/pages/Dashboard/Dashboard.css @@ -0,0 +1,109 @@ +.dashboard-container { + padding: 20px 24px 40px; + background-color: #ffffff; + margin-top: -15px; /* 减小与导航栏的间距 */ + max-width: 1600px; /* 设置最大宽度 */ + margin-left: auto; /* 水平居中 */ + margin-right: auto; +} + +.stat-card { + background: linear-gradient(135deg, #2185d0 0%, #1678c2 100%) !important; + color: white !important; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1) !important; + transition: transform 0.2s ease !important; + margin-bottom: 1rem !important; +} + +.stat-card:hover { + transform: translateY(-5px); +} + +.stat-card .statistic { + color: white !important; +} + +.charts-grid { + margin-bottom: 1rem !important; +} + +.charts-grid .column { + padding: 0.5rem !important; +} + +.chart-card { + height: 100%; + box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04) !important; + border: none !important; + border-radius: 16px !important; + padding: 8px!important; +} + +.chart-container { + margin-top: 2px; + padding: 16px; + background-color: white; + border-radius: 12px; +} + +.ui.card > .content > .header { + color: #2B3674; + font-size: 1.2em; + margin-bottom: 15px; + display: flex; + justify-content: space-between; + align-items: center; + font-weight: 600; + gap: 12px; /* 增加标题和数值之间的间距 */ +} + +.stat-value { + color: #4318FF; + font-weight: bold; + font-size: 1.1em; + background: rgba(67, 24, 255, 0.1); + padding: 4px 12px; + border-radius: 8px; + white-space: nowrap; /* 防止数值换行 */ + margin-left: 16px; +} + +/* 优化图表响应式布局 */ +@media (max-width: 768px) { + .dashboard-container { + padding: 10px 16px; /* 移动端也相应减小内边距 */ + max-width: 100%; /* 移动端占满全宽 */ + } + + .chart-container { + padding: 12px; + } + + .charts-grid .column { + padding: 0.25rem !important; + } +} + +/* 设置页面的 Tab 样式 */ +.settings-tab { + margin-top: 1rem !important; + border-bottom: none !important; +} + +.settings-tab .item { + color: #000 !important; + font-weight: 500 !important; + padding: 0.8rem 1.2rem !important; +} + +.settings-tab .active.item { + color: #000 !important; + font-weight: 600 !important; + border-color: #000 !important; +} + +.ui.tab.segment { + border: none !important; + box-shadow: none !important; + padding: 1rem 0 !important; +} \ No newline at end of file diff --git a/web/default/src/pages/Dashboard/index.js b/web/default/src/pages/Dashboard/index.js new file mode 100644 index 00000000..21151519 --- /dev/null +++ b/web/default/src/pages/Dashboard/index.js @@ -0,0 +1,460 @@ +import React, { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Card, Grid } from 'semantic-ui-react'; +import { + Bar, + BarChart, + CartesianGrid, + Legend, + Line, + LineChart, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from 'recharts'; +import axios from 'axios'; +import './Dashboard.css'; + +// 在 Dashboard 组件内添加自定义配置 +const chartConfig = { + lineChart: { + style: { + background: '#fff', + borderRadius: '8px', + }, + line: { + strokeWidth: 2, + dot: false, + activeDot: { r: 4 }, + }, + grid: { + vertical: false, + horizontal: true, + opacity: 0.1, + }, + }, + colors: { + requests: '#4318FF', + quota: '#00B5D8', + tokens: '#6C63FF', + }, + barColors: [ + '#4318FF', // 深紫色 + '#00B5D8', // 青色 + '#6C63FF', // 紫色 + '#05CD99', // 绿色 + '#FFB547', // 橙色 + '#FF5E7D', // 粉色 + '#41B883', // 翠绿 + '#7983FF', // 淡紫 + '#FF8F6B', // 珊瑚色 + '#49BEFF', // 天蓝 + ], +}; + +const Dashboard = () => { + const { t } = useTranslation(); + const [data, setData] = useState([]); + const [summaryData, setSummaryData] = useState({ + todayRequests: 0, + todayQuota: 0, + todayTokens: 0, + }); + + useEffect(() => { + fetchDashboardData(); + }, []); + + const fetchDashboardData = async () => { + try { + const response = await axios.get('/api/user/dashboard'); + if (response.data.success) { + const dashboardData = response.data.data || []; + setData(dashboardData); + calculateSummary(dashboardData); + } + } catch (error) { + console.error('Failed to fetch dashboard data:', error); + setData([]); + calculateSummary([]); + } + }; + + const calculateSummary = (dashboardData) => { + if (!Array.isArray(dashboardData) || dashboardData.length === 0) { + setSummaryData({ + todayRequests: 0, + todayQuota: 0, + todayTokens: 0, + }); + return; + } + + const today = new Date().toISOString().split('T')[0]; + const todayData = dashboardData.filter((item) => item.Day === today); + + const summary = { + todayRequests: todayData.reduce( + (sum, item) => sum + item.RequestCount, + 0 + ), + todayQuota: + todayData.reduce((sum, item) => sum + item.Quota, 0) / 1000000, + todayTokens: todayData.reduce( + (sum, item) => sum + item.PromptTokens + item.CompletionTokens, + 0 + ), + }; + + setSummaryData(summary); + }; + + // 处理数据以供折线图使用,补充缺失的日期 + const processTimeSeriesData = () => { + const dailyData = {}; + + // 获取日期范围 + const dates = data.map((item) => item.Day); + const maxDate = new Date(); // 总是使用今天作为最后一天 + let minDate = + dates.length > 0 + ? new Date(Math.min(...dates.map((d) => new Date(d)))) + : new Date(); + + // 确保至少显示5天的数据 + const fiveDaysAgo = new Date(); + fiveDaysAgo.setDate(fiveDaysAgo.getDate() - 4); // -4是因为包含今天 + if (minDate > fiveDaysAgo) { + minDate = fiveDaysAgo; + } + + // 生成所有日期 + for (let d = new Date(minDate); d <= maxDate; d.setDate(d.getDate() + 1)) { + const dateStr = d.toISOString().split('T')[0]; + dailyData[dateStr] = { + date: dateStr, + requests: 0, + quota: 0, + tokens: 0, + }; + } + + // 填充实际数据 + data.forEach((item) => { + dailyData[item.Day].requests += item.RequestCount; + dailyData[item.Day].quota += item.Quota / 1000000; + dailyData[item.Day].tokens += item.PromptTokens + item.CompletionTokens; + }); + + return Object.values(dailyData).sort((a, b) => + a.date.localeCompare(b.date) + ); + }; + + // 处理数据以供堆叠柱状图使用 + const processModelData = () => { + const timeData = {}; + + // 获取日期范围 + const dates = data.map((item) => item.Day); + const maxDate = new Date(); // 总是使用今天作为最后一天 + let minDate = + dates.length > 0 + ? new Date(Math.min(...dates.map((d) => new Date(d)))) + : new Date(); + + // 确保至少显示5天的数据 + const fiveDaysAgo = new Date(); + fiveDaysAgo.setDate(fiveDaysAgo.getDate() - 4); // -4是因为包含今天 + if (minDate > fiveDaysAgo) { + minDate = fiveDaysAgo; + } + + // 生成所有日期 + for (let d = new Date(minDate); d <= maxDate; d.setDate(d.getDate() + 1)) { + const dateStr = d.toISOString().split('T')[0]; + timeData[dateStr] = { + date: dateStr, + }; + + // 初始化所有模型的数据为0 + const models = [...new Set(data.map((item) => item.ModelName))]; + models.forEach((model) => { + timeData[dateStr][model] = 0; + }); + } + + // 填充实际数据 + data.forEach((item) => { + timeData[item.Day][item.ModelName] = + item.PromptTokens + item.CompletionTokens; + }); + + return Object.values(timeData).sort((a, b) => a.date.localeCompare(b.date)); + }; + + // 获取所有唯一的模型名称 + const getUniqueModels = () => { + return [...new Set(data.map((item) => item.ModelName))]; + }; + + const timeSeriesData = processTimeSeriesData(); + const modelData = processModelData(); + const models = getUniqueModels(); + + // 生成随机颜色 + const getRandomColor = (index) => { + return chartConfig.barColors[index % chartConfig.barColors.length]; + }; + + // 添加一个日期格式化函数 + const formatDate = (dateStr) => { + const date = new Date(dateStr); + return date.toLocaleDateString('zh-CN', { + month: 'numeric', + day: 'numeric', + }); + }; + + // 修改所有 XAxis 配置 + const xAxisConfig = { + dataKey: 'date', + axisLine: false, + tickLine: false, + tick: { + fontSize: 12, + fill: '#A3AED0', + textAnchor: 'middle', // 文本居中对齐 + }, + tickFormatter: formatDate, + interval: 0, + minTickGap: 5, + padding: { left: 30, right: 30 }, // 增加两侧的内边距,确保首尾标签完整显示 + }; + + return ( +
+ {/* 三个并排的折线图 */} + + + + + + {t('dashboard.charts.requests.title')} + {/* {summaryData.todayRequests} */} + +
+ + + + + + [ + value, + t('dashboard.charts.requests.tooltip'), + ]} + labelFormatter={(label) => + `${t( + 'dashboard.statistics.tooltip.date' + )}: ${formatDate(label)}` + } + /> + + + +
+
+
+
+ + + + + + {t('dashboard.charts.quota.title')} + {/* + ${summaryData.todayQuota.toFixed(3)} + */} + +
+ + + + + + [ + value.toFixed(6), + t('dashboard.charts.quota.tooltip'), + ]} + labelFormatter={(label) => + `${t( + 'dashboard.statistics.tooltip.date' + )}: ${formatDate(label)}` + } + /> + + + +
+
+
+
+ + + + + + {t('dashboard.charts.tokens.title')} + {/* {summaryData.todayTokens} */} + +
+ + + + + + [ + value, + t('dashboard.charts.tokens.tooltip'), + ]} + labelFormatter={(label) => + `${t( + 'dashboard.statistics.tooltip.date' + )}: ${formatDate(label)}` + } + /> + + + +
+
+
+
+
+ + {/* 模型使用统计 */} + + + {t('dashboard.statistics.title')} +
+ + + + + + + `${t('dashboard.statistics.tooltip.date')}: ${formatDate( + label + )}` + } + /> + + {models.map((model, index) => ( + + ))} + + +
+
+
+
+ ); +}; + +export default Dashboard; diff --git a/web/default/src/pages/Home/index.js b/web/default/src/pages/Home/index.js index 63d6d77a..5e764abb 100644 --- a/web/default/src/pages/Home/index.js +++ b/web/default/src/pages/Home/index.js @@ -1,24 +1,29 @@ import React, { useContext, useEffect, useState } from 'react'; -import { Card, Grid, Header, Segment } from 'semantic-ui-react'; +import { useTranslation } from 'react-i18next'; +import { Card, Grid, Header } from 'semantic-ui-react'; import { API, showError, showNotice, timestamp2string } from '../../helpers'; import { StatusContext } from '../../context/Status'; import { marked } from 'marked'; +import { UserContext } from '../../context/User'; +import { Link } from 'react-router-dom'; const Home = () => { + const { t } = useTranslation(); const [statusState, statusDispatch] = useContext(StatusContext); const [homePageContentLoaded, setHomePageContentLoaded] = useState(false); const [homePageContent, setHomePageContent] = useState(''); + const [userState] = useContext(UserContext); const displayNotice = async () => { const res = await API.get('/api/notice'); const { success, message, data } = res.data; if (success) { let oldNotice = localStorage.getItem('notice'); - if (data !== oldNotice && data !== '') { - const htmlNotice = marked(data); - showNotice(htmlNotice, true); - localStorage.setItem('notice', data); - } + if (data !== oldNotice && data !== '') { + const htmlNotice = marked(data); + showNotice(htmlNotice, true); + localStorage.setItem('notice', data); + } } else { showError(message); } @@ -37,7 +42,7 @@ const Home = () => { localStorage.setItem('home_page_content', content); } else { showError(message); - setHomePageContent('加载首页内容失败...'); + setHomePageContent(t('home.loading_failed')); } setHomePageContentLoaded(true); }; @@ -51,81 +56,242 @@ const Home = () => { displayNotice().then(); displayHomePageContent().then(); }, []); + return ( <> - { - homePageContentLoaded && homePageContent === '' ? <> - -
系统状况
- - - - - 系统信息 - 系统信息总览 - -

名称:{statusState?.status?.system_name}

-

版本:{statusState?.status?.version ? statusState?.status?.version : "unknown"}

-

- 源码: - + + + + {t('home.welcome.title')} + + +

{t('home.welcome.description')}

+ {!userState.user &&

{t('home.welcome.login_notice')}

} +
+
+
+ + + +
{t('home.system_status.title')}
+
+ + + + + +
+ {t('home.system_status.info.title')} +
+
+ +

- https://github.com/songquanpeng/one-api - -

-

启动时间:{getStartTimeString()}

- - - -
- - - - 系统配置 - 系统配置总览 - -

- 邮箱验证: - {statusState?.status?.email_verification === true - ? '已启用' - : '未启用'} -

-

- GitHub 身份验证: - {statusState?.status?.github_oauth === true - ? '已启用' - : '未启用'} -

-

- 微信身份验证: - {statusState?.status?.wechat_login === true - ? '已启用' - : '未启用'} -

-

- Turnstile 用户校验: - {statusState?.status?.turnstile_check === true - ? '已启用' - : '未启用'} -

-
-
-
-
-
-
- : <> - { - homePageContent.startsWith('https://') ?