diff --git a/common/log_text.zh-CN.json b/common/log_text.zh-CN.json index 9dd849c165..2bc7557849 100644 --- a/common/log_text.zh-CN.json +++ b/common/log_text.zh-CN.json @@ -525,6 +525,7 @@ "failed to invalidate tokens cache for user %d: %s": "清除用户 %d 的令牌缓存失败: %s", "failed to invalidate user cache after hard deleting user %d: %v": "永久删除用户 %d 后清除用户缓存失败: %v", "failed to load custom OAuth providers: %s": "加载自定义 OAuth 提供商失败: %s", + "failed to load model usage for the model square: %s": "加载模型广场的模型用量失败: %s", "failed to load options from database: %s": "从数据库加载设置失败: %s", "failed to load tool prices, using hardcoded fallbacks: %s": "加载工具价格失败,将使用硬编码兜底: %s", "failed to marshal gemini response: %s": "序列化 Gemini 响应失败: %s", diff --git a/controller/model_list_test.go b/controller/model_list_test.go index 0c4ece72db..d181463ee2 100644 --- a/controller/model_list_test.go +++ b/controller/model_list_test.go @@ -261,6 +261,97 @@ func TestModelSquareGroupVisibility(t *testing.T) { } } +func TestModelSquareOrderFollowsSavedSetting(t *testing.T) { + originalGroups := setting.UserUsableGroups2JSONString() + originalOrder := *operation_setting.GetModelSquareSetting() + originalDataExport := common.DataExportEnabled + t.Cleanup(func() { + require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(originalGroups)) + *operation_setting.GetModelSquareSetting() = originalOrder + common.DataExportEnabled = originalDataExport + }) + + for _, dialect := range []struct{ kind, env string }{{"sqlite", ""}, {"mysql", "TEST_MYSQL_DSN"}, {"postgres", "TEST_POSTGRES_DSN"}} { + t.Run(dialect.kind, func(t *testing.T) { + if dialect.env != "" && os.Getenv(dialect.env) == "" { + t.Skip("set " + dialect.env + " to run this database") + } + db := modelManagementDB(t, dialect.kind, os.Getenv(dialect.env)) + // The service caches usage across databases, so usage ordering is + // covered in the service tests and the query is checked directly below. + common.DataExportEnabled = false + *operation_setting.GetModelSquareSetting() = operation_setting.ModelSquareSetting{SortMode: "manual", SortMetric: "tokens", SortDays: 7, SortModels: []string{}} + require.NoError(t, setting.UpdateUserUsableGroupsByJSONString(`{"default":"Public"}`)) + vendor := model.Vendor{Name: "Acme", Icon: "Acme.Color"} + require.NoError(t, db.Create(&vendor).Error) + require.NoError(t, db.Create(&model.Model{ModelName: "vip-only", Icon: "Vip.Color", VendorID: vendor.Id, Status: 1}).Error) + require.NoError(t, db.Create(&[]model.Ability{ + {Model: "alpha", Group: "default", ChannelId: 1, Enabled: true}, + {Model: "gamma", Group: "default", ChannelId: 1, Enabled: true}, + {Model: "vip-only", Group: "vip", ChannelId: 1, Enabled: true}, + }).Error) + model.InvalidatePricingCache() + t.Cleanup(model.InvalidatePricingCache) + + manual := []string{"gamma", "alpha"} + for _, step := range []struct { + key, value string + rejected bool + want []string + }{ + {want: []string{}}, + {key: "model_square_setting.sort_models", value: `["gamma","vip-only","alpha","gamma"]`, want: manual}, + {key: "model_square_setting.sort_mode", value: "random", rejected: true, want: manual}, + {key: "model_square_setting.sort_metric", value: "cost", rejected: true, want: manual}, + {key: "model_square_setting.sort_days", value: "3", rejected: true, want: manual}, + {key: "model_square_setting.sort_models", value: `"gamma"`, rejected: true, want: manual}, + } { + if step.key != "" { + err := model.UpdateOption(step.key, step.value) + if step.rejected { + require.Error(t, err, step.key) + } else { + require.NoError(t, err, step.key) + } + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodGet, "/api/pricing", nil) + GetPricing(ctx) + require.Equal(t, http.StatusOK, recorder.Code) + var response struct { + ModelOrder map[string][]string `json:"model_order"` + } + require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &response)) + assert.Equal(t, map[string][]string{"recommended": step.want, "requests": {}, "tokens": {}}, response.ModelOrder, step.key) + } + + // The admin preview offers the models of every group. + assert.ElementsMatch(t, []modelSquareUsage{ + {ModelName: "alpha"}, + {ModelName: "gamma"}, + {ModelName: "vip-only", Icon: "Vip.Color", VendorName: "Acme", VendorIcon: "Acme.Color"}, + }, modelSquareData[[]modelSquareUsage](t, GetModelSquareUsage, "/api/models/square_usage?days=7", "")) + + require.NoError(t, db.AutoMigrate(&model.QuotaData{})) + now := time.Now().Unix() + require.NoError(t, db.Create(&[]model.QuotaData{ + {UserID: 1, Username: "a", ModelName: "alpha", CreatedAt: now - 3600, Count: 3, TokenUsed: 100}, + {UserID: 2, Username: "b", ModelName: "alpha", CreatedAt: now - 7200, Count: 2}, + {UserID: 1, Username: "a", ModelName: "vip-only", CreatedAt: now - 3600, Count: 1}, + {UserID: 1, Username: "a", ModelName: "gamma", CreatedAt: now - 8*24*3600, Count: 9, TokenUsed: 900}, + {UserID: 1, Username: "a", ModelName: "", CreatedAt: now - 3600, Count: 4, TokenUsed: 40}, + }).Error) + totals, err := model.GetModelUsageTotals(now-7*24*3600, now) + require.NoError(t, err) + assert.ElementsMatch(t, []model.ModelUsageTotal{ + {ModelName: "alpha", Requests: 5, Tokens: 100}, + {ModelName: "vip-only", Requests: 1}, + }, totals) + }) + } +} + func decodeUserModelsResponse(t *testing.T, recorder *httptest.ResponseRecorder) []string { t.Helper() diff --git a/controller/pricing.go b/controller/pricing.go index 43eb81712d..d6bf0d4cfd 100644 --- a/controller/pricing.go +++ b/controller/pricing.go @@ -1,10 +1,14 @@ package controller import ( + "net/http" + "strconv" + "github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/model" "github.com/QuantumNous/new-api/service" + "github.com/QuantumNous/new-api/setting/operation_setting" "github.com/QuantumNous/new-api/setting/ratio_setting" "github.com/gin-gonic/gin" @@ -60,10 +64,59 @@ func GetPricing(c *gin.Context) { "usable_group": usableGroup, "supported_endpoint": model.GetSupportedEndpointMap(), "auto_groups": service.GetUserAutoGroup(userGroup), + "model_order": service.BuildModelSquareOrder(pricing), "pricing_version": "a42d372ccf0b5dd13ecf71203521f9d2", }) } +type modelSquareUsage struct { + ModelName string `json:"model_name"` + Icon string `json:"icon,omitempty"` + VendorName string `json:"vendor_name,omitempty"` + VendorIcon string `json:"vendor_icon,omitempty"` + Requests int64 `json:"requests"` + Tokens int64 `json:"tokens"` +} + +// GetModelSquareUsage lists every model of the model square, whichever group +// can see it, with its usage for the order preview. +func GetModelSquareUsage(c *gin.Context) { + days := c.DefaultQuery("days", "7") + if err := operation_setting.ValidateModelSquareOption("model_square_setting.sort_days", days); err != nil { + common.ApiErrorStatus(c, http.StatusBadRequest, err) + return + } + dayCount, _ := strconv.Atoi(days) + totals, err := service.GetModelUsageTotals(dayCount) + if err != nil { + common.ApiError(c, err) + return + } + usage := make(map[string]model.ModelUsageTotal, len(totals)) + for _, total := range totals { + usage[total.ModelName] = total + } + pricing := model.GetPricing() + vendors := make(map[int]model.PricingVendor) + for _, vendor := range model.GetVendors() { + vendors[vendor.ID] = vendor + } + rows := make([]modelSquareUsage, 0, len(pricing)) + for _, item := range pricing { + vendor := vendors[item.VendorID] + total := usage[item.ModelName] + rows = append(rows, modelSquareUsage{ + ModelName: item.ModelName, + Icon: item.Icon, + VendorName: vendor.Name, + VendorIcon: vendor.Icon, + Requests: total.Requests, + Tokens: total.Tokens, + }) + } + common.ApiSuccess(c, rows) +} + func ResetModelRatio(c *gin.Context) { defaultStr := ratio_setting.DefaultModelRatio2JSONString() err := model.UpdateOption("ModelRatio", defaultStr) diff --git a/middleware/access_token_routes.go b/middleware/access_token_routes.go index 129338f981..8419df5372 100644 --- a/middleware/access_token_routes.go +++ b/middleware/access_token_routes.go @@ -282,6 +282,7 @@ var accessTokenRouteRules = map[string]accessTokenRouteRule{ "POST /api/models/sync_upstream": accessTokenScopeRule("model:write"), "POST /api/models/delete": accessTokenScopeRule("model:write"), "GET /api/models/missing": accessTokenScopeRule("model:read"), + "GET /api/models/square_usage": accessTokenScopeRule("log:read"), "GET /api/models/": accessTokenScopeRule("model:read"), "GET /api/models/search": accessTokenScopeRule("model:read"), "GET /api/models/:id": accessTokenScopeRule("model:read"), diff --git a/model/option.go b/model/option.go index a630aa643a..abd49b95dd 100644 --- a/model/option.go +++ b/model/option.go @@ -246,6 +246,9 @@ func validateOptionValue(key string, value string) error { if err := operation_setting.ValidateEpaySignOption(key, value); err != nil { return err } + if err := operation_setting.ValidateModelSquareOption(key, value); err != nil { + return err + } if key == "EmailProvider" || key == "ResendApiKey" || key == "ResendFrom" { if key == "EmailProvider" && value != "smtp" && value != "resend" { return common.NewMessage("Email sending method must be SMTP or Resend") diff --git a/model/usedata_rankings.go b/model/usedata_rankings.go index a16193d9b3..7da79f9c52 100644 --- a/model/usedata_rankings.go +++ b/model/usedata_rankings.go @@ -31,6 +31,25 @@ func GetRankingQuotaTotals(startTime int64, endTime int64) ([]RankingQuotaTotal, return rows, err } +type ModelUsageTotal struct { + ModelName string `json:"model_name"` + Requests int64 `json:"requests"` + Tokens int64 `json:"tokens"` +} + +// GetModelUsageTotals sums requests and tokens per model, including models +// that used no tokens. +func GetModelUsageTotals(startTime int64, endTime int64) ([]ModelUsageTotal, error) { + var rows []ModelUsageTotal + query := DB.Table("quota_data"). + Select("model_name, sum(count) as requests, sum(token_used) as tokens"). + Where("model_name <> ''"). + Group("model_name") + query = applyRankingQuotaTimeRange(query, startTime, endTime) + err := query.Find(&rows).Error + return rows, err +} + func GetRankingQuotaBuckets(startTime int64, endTime int64, bucketSize int64) ([]RankingQuotaBucket, error) { if bucketSize <= 0 { bucketSize = 3600 diff --git a/router/api-router.go b/router/api-router.go index 00ddf6964d..46195c29c1 100644 --- a/router/api-router.go +++ b/router/api-router.go @@ -416,6 +416,7 @@ func SetApiRouter(router *gin.Engine) { modelsRoute.POST("/sync_upstream", controller.SyncUpstreamModels) modelsRoute.POST("/delete", controller.BatchDeleteModelMeta) modelsRoute.GET("/missing", controller.GetMissingModels) + modelsRoute.GET("/square_usage", controller.GetModelSquareUsage) modelsRoute.GET("/", controller.GetAllModelsMeta) modelsRoute.GET("/search", controller.SearchModelsMeta) modelsRoute.GET("/:id", controller.GetModelMeta) diff --git a/service/model_square_order.go b/service/model_square_order.go new file mode 100644 index 0000000000..ea9299ef2d --- /dev/null +++ b/service/model_square_order.go @@ -0,0 +1,119 @@ +package service + +import ( + "cmp" + "slices" + "strings" + "sync" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/model" + "github.com/QuantumNous/new-api/setting/operation_setting" +) + +// ModelSquareOrder lists model names for the model square sorts. Models +// missing from a list follow it by name. It holds no usage figures, because +// the model square can be public while the rankings page is off. +type ModelSquareOrder struct { + Recommended []string `json:"recommended"` + Requests []string `json:"requests"` + Tokens []string `json:"tokens"` +} + +type modelUsageCacheItem struct { + expiresAt time.Time + totals []model.ModelUsageTotal +} + +var ( + modelUsageCacheMu sync.Mutex + modelUsageCache = map[int]modelUsageCacheItem{} +) + +// GetModelUsageTotals returns each model's usage over the last days, cached +// like the rankings. Without dashboard data there is no usage. +func GetModelUsageTotals(days int) ([]model.ModelUsageTotal, error) { + if !common.DataExportEnabled { + return nil, nil + } + now := time.Now() + modelUsageCacheMu.Lock() + item, ok := modelUsageCache[days] + modelUsageCacheMu.Unlock() + if ok && now.Before(item.expiresAt) { + return item.totals, nil + } + + totals, err := model.GetModelUsageTotals(now.AddDate(0, 0, -days).Unix(), now.Unix()) + if err != nil { + return nil, err + } + modelUsageCacheMu.Lock() + modelUsageCache[days] = modelUsageCacheItem{expiresAt: now.Add(rankingCacheTTL), totals: totals} + modelUsageCacheMu.Unlock() + return totals, nil +} + +// BuildModelSquareOrder orders the listed models for the model square sorts. +// Names that are not listed are left out. +func BuildModelSquareOrder(pricing []model.Pricing) ModelSquareOrder { + listed := make(map[string]struct{}, len(pricing)) + for _, item := range pricing { + listed[item.ModelName] = struct{}{} + } + setting := operation_setting.GetModelSquareSetting() + totals, err := GetModelUsageTotals(setting.SortDays) + if err != nil { + common.SysError(common.LogText("failed to load model usage for the model square: %s", err.Error())) + } + order := ModelSquareOrder{ + Requests: modelNamesByUsage(totals, operation_setting.ModelSquareMetricRequests, listed), + Tokens: modelNamesByUsage(totals, operation_setting.ModelSquareMetricTokens, listed), + } + byMetric := order.Tokens + if setting.SortMetric == operation_setting.ModelSquareMetricRequests { + byMetric = order.Requests + } + if setting.SortMode == operation_setting.ModelSquareSortUsage { + order.Recommended = byMetric + return order + } + + order.Recommended = make([]string, 0, len(setting.SortModels)) + for _, name := range setting.SortModels { + if _, ok := listed[name]; ok && !slices.Contains(order.Recommended, name) { + order.Recommended = append(order.Recommended, name) + } + } + if setting.SortMode == operation_setting.ModelSquareSortMixed { + pinned := len(order.Recommended) + for _, name := range byMetric { + if !slices.Contains(order.Recommended[:pinned], name) { + order.Recommended = append(order.Recommended, name) + } + } + } + return order +} + +// modelNamesByUsage lists the listed models that have usage of the metric, +// most used first and equal usage in byte order, as the web console does. +func modelNamesByUsage(totals []model.ModelUsageTotal, metric string, listed map[string]struct{}) []string { + usage := make(map[string]int64, len(totals)) + names := make([]string, 0, len(totals)) + for _, total := range totals { + value := total.Tokens + if metric == operation_setting.ModelSquareMetricRequests { + value = total.Requests + } + if _, ok := listed[total.ModelName]; ok && value > 0 { + usage[total.ModelName] = value + names = append(names, total.ModelName) + } + } + slices.SortFunc(names, func(a, b string) int { + return cmp.Or(cmp.Compare(usage[b], usage[a]), strings.Compare(a, b)) + }) + return names +} diff --git a/service/model_square_order_test.go b/service/model_square_order_test.go new file mode 100644 index 0000000000..206a13011f --- /dev/null +++ b/service/model_square_order_test.go @@ -0,0 +1,114 @@ +package service + +import ( + "testing" + "time" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/model" + "github.com/QuantumNous/new-api/setting/operation_setting" + "github.com/glebarez/sqlite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/gorm" +) + +func TestBuildModelSquareOrder(t *testing.T) { + database, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + require.NoError(t, err) + sqlDB, err := database.DB() + require.NoError(t, err) + sqlDB.SetMaxOpenConns(1) + require.NoError(t, database.AutoMigrate(&model.QuotaData{})) + previousDB := model.DB + previousOrder := *operation_setting.GetModelSquareSetting() + previousDataExport := common.DataExportEnabled + model.DB = database + t.Cleanup(func() { + model.DB = previousDB + *operation_setting.GetModelSquareSetting() = previousOrder + common.DataExportEnabled = previousDataExport + modelUsageCache = map[int]modelUsageCacheItem{} + _ = sqlDB.Close() + }) + + hourAgo := time.Now().Add(-time.Hour).Unix() + require.NoError(t, database.Create(&[]model.QuotaData{ + {ModelName: "gamma", CreatedAt: hourAgo, Count: 5, TokenUsed: 900}, + // Ties with gamma: byte order puts upper case first. + {ModelName: "Kappa", CreatedAt: hourAgo, Count: 5, TokenUsed: 900}, + {ModelName: "beta", CreatedAt: hourAgo, Count: 9, TokenUsed: 100}, + {ModelName: "beta", CreatedAt: hourAgo - 3600, Count: 1, TokenUsed: 50}, + // Per-call models can have requests without tokens. + {ModelName: "delta", CreatedAt: hourAgo, Count: 3}, + {ModelName: "alpha", CreatedAt: hourAgo - 10*24*3600, Count: 99, TokenUsed: 9999}, + {ModelName: "retired", CreatedAt: hourAgo, Count: 50, TokenUsed: 5000}, + }).Error) + pricing := []model.Pricing{{ModelName: "alpha"}, {ModelName: "beta"}, {ModelName: "delta"}, {ModelName: "gamma"}, {ModelName: "Kappa"}, {ModelName: "zeta"}} + requests := []string{"beta", "Kappa", "gamma", "delta"} + tokens := []string{"Kappa", "gamma", "beta"} + + for _, tc := range []struct { + name string + setting operation_setting.ModelSquareSetting + dataExport bool + want ModelSquareOrder + }{ + { + name: "no config keeps name order", + setting: operation_setting.ModelSquareSetting{SortMode: "manual", SortMetric: "tokens", SortDays: 7, SortModels: []string{}}, + dataExport: true, + want: ModelSquareOrder{Recommended: []string{}, Requests: requests, Tokens: tokens}, + }, + { + name: "manual drops unlisted and repeated names", + setting: operation_setting.ModelSquareSetting{SortMode: "manual", SortMetric: "tokens", SortDays: 7, SortModels: []string{"zeta", "retired", "alpha", "zeta"}}, + dataExport: true, + want: ModelSquareOrder{Recommended: []string{"zeta", "alpha"}, Requests: requests, Tokens: tokens}, + }, + { + name: "most requests", + setting: operation_setting.ModelSquareSetting{SortMode: "usage", SortMetric: "requests", SortDays: 7}, + dataExport: true, + want: ModelSquareOrder{Recommended: requests, Requests: requests, Tokens: tokens}, + }, + { + name: "most tokens leaves models without tokens to the name tail", + setting: operation_setting.ModelSquareSetting{SortMode: "usage", SortMetric: "tokens", SortDays: 7}, + dataExport: true, + want: ModelSquareOrder{Recommended: tokens, Requests: requests, Tokens: tokens}, + }, + { + name: "pinned models come before the most used", + setting: operation_setting.ModelSquareSetting{SortMode: "mixed", SortMetric: "tokens", SortDays: 7, SortModels: []string{"delta", "retired", "beta"}}, + dataExport: true, + want: ModelSquareOrder{Recommended: []string{"delta", "beta", "Kappa", "gamma"}, Requests: requests, Tokens: tokens}, + }, + { + name: "longer period counts older usage", + setting: operation_setting.ModelSquareSetting{SortMode: "usage", SortMetric: "tokens", SortDays: 30}, + dataExport: true, + want: ModelSquareOrder{Recommended: []string{"alpha", "Kappa", "gamma", "beta"}, Requests: []string{"alpha", "beta", "Kappa", "gamma", "delta"}, Tokens: []string{"alpha", "Kappa", "gamma", "beta"}}, + }, + { + name: "without dashboard data usage sorts fall back to names", + setting: operation_setting.ModelSquareSetting{SortMode: "mixed", SortMetric: "requests", SortDays: 7, SortModels: []string{"gamma"}}, + want: ModelSquareOrder{Recommended: []string{"gamma"}, Requests: []string{}, Tokens: []string{}}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + *operation_setting.GetModelSquareSetting() = tc.setting + common.DataExportEnabled = tc.dataExport + modelUsageCache = map[int]modelUsageCacheItem{} + + assert.Equal(t, tc.want, BuildModelSquareOrder(pricing)) + }) + } + + // The public model square gets names only, never usage figures. + *operation_setting.GetModelSquareSetting() = operation_setting.ModelSquareSetting{SortMode: "usage", SortMetric: "requests", SortDays: 7} + common.DataExportEnabled = true + encoded, err := common.Marshal(BuildModelSquareOrder(pricing)) + require.NoError(t, err) + assert.JSONEq(t, `{"recommended":["beta","Kappa","gamma","delta"],"requests":["beta","Kappa","gamma","delta"],"tokens":["Kappa","gamma","beta"]}`, string(encoded)) +} diff --git a/setting/operation_setting/model_square_setting.go b/setting/operation_setting/model_square_setting.go new file mode 100644 index 0000000000..965a6b9b1d --- /dev/null +++ b/setting/operation_setting/model_square_setting.go @@ -0,0 +1,66 @@ +package operation_setting + +import ( + "slices" + "strings" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/setting/config" +) + +const ( + ModelSquareSortManual = "manual" + ModelSquareSortUsage = "usage" + ModelSquareSortMixed = "mixed" + + ModelSquareMetricRequests = "requests" + ModelSquareMetricTokens = "tokens" +) + +// ModelSquareSetting holds the Recommended order of the model square. +type ModelSquareSetting struct { + SortMode string `json:"sort_mode"` // manual, usage or mixed + SortMetric string `json:"sort_metric"` // usage metric: requests or tokens + SortDays int `json:"sort_days"` // usage period in days: 1, 7 or 30 + SortModels []string `json:"sort_models"` // manual order, or the pinned models in mixed mode +} + +// An empty manual list keeps the model square in name order. +var modelSquareSetting = ModelSquareSetting{ + SortMode: ModelSquareSortManual, + SortMetric: ModelSquareMetricTokens, + SortDays: 7, + SortModels: []string{}, +} + +func init() { + config.GlobalConfig.Register("model_square_setting", &modelSquareSetting) +} + +func GetModelSquareSetting() *ModelSquareSetting { + return &modelSquareSetting +} + +// ValidateModelSquareOption rejects model square order values the square cannot use. +func ValidateModelSquareOption(key, value string) error { + setting, ok := strings.CutPrefix(key, "model_square_setting.") + if !ok { + return nil + } + valid := false + switch setting { + case "sort_mode": + valid = slices.Contains([]string{ModelSquareSortManual, ModelSquareSortUsage, ModelSquareSortMixed}, value) + case "sort_metric": + valid = value == ModelSquareMetricRequests || value == ModelSquareMetricTokens + case "sort_days": + valid = slices.Contains([]string{"1", "7", "30"}, value) + case "sort_models": + var names []string + valid = common.UnmarshalJsonStr(value, &names) == nil + } + if !valid { + return common.NewMessage("Invalid model square order setting") + } + return nil +} diff --git a/web/src/features/models/__tests__/model-square-order.test.tsx b/web/src/features/models/__tests__/model-square-order.test.tsx new file mode 100644 index 0000000000..bde8c04f52 --- /dev/null +++ b/web/src/features/models/__tests__/model-square-order.test.tsx @@ -0,0 +1,206 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { toast } from 'sonner' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { api } from '@/lib/api' + +import { ModelSquareOrderDialog } from '../components/dialogs/model-square-order-dialog' + +function mockApi( + saved: Record, + usage: Record = {} +) { + vi.spyOn(api, 'get').mockImplementation(async (url: string) => { + if (url === '/api/option/') { + const data = Object.entries(saved).map(([key, value]) => ({ + key, + value, + })) + return { data: { success: true, data } } + } + if (url === '/api/models/square_usage') { + // Every square model, including ones only other groups can see + const data = ['alpha', 'beta', 'gamma'].map((name) => ({ + model_name: name, + vendor_name: 'Acme', + requests: usage[name]?.requests ?? 0, + tokens: usage[name]?.tokens ?? 0, + })) + return { data: { success: true, data } } + } + return { data: { success: true, data: {} } } + }) + return vi.spyOn(api, 'put').mockResolvedValue({ data: { success: true } }) +} + +function renderDialog(onOpenChange = vi.fn()) { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + }) + const view = render( + + + + ) + return { + rerender: (open: boolean) => + view.rerender( + + + + ), + } +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('model square order dialog', () => { + it('keeps list edits as a draft and saves only the changed setting', async () => { + const put = mockApi({ + 'model_square_setting.sort_mode': 'manual', + 'model_square_setting.sort_models': '["beta","alpha"]', + }) + const user = userEvent.setup() + renderDialog() + + await user.click( + await screen.findByRole('button', { name: 'Move alpha up' }) + ) + await user.click(screen.getByRole('button', { name: 'Remove beta' })) + await user.click(screen.getByRole('combobox', { name: 'Add model' })) + await user.click(await screen.findByRole('option', { name: /gamma/ })) + expect(screen.getByRole('button', { name: 'Remove gamma' })).toBeVisible() + expect(put).not.toHaveBeenCalled() + + await user.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(put).toHaveBeenCalledTimes(1)) + expect(put).toHaveBeenCalledWith('/api/option/', { + key: 'model_square_setting.sort_models', + value: '["alpha","gamma"]', + }) + }) + + it('shows one success toast for several changed settings', async () => { + const put = mockApi({ 'model_square_setting.sort_mode': 'manual' }) + const success = vi.spyOn(toast, 'success') + const onOpenChange = vi.fn() + const user = userEvent.setup() + renderDialog(onOpenChange) + + await user.click(await screen.findByRole('button', { name: 'Most used' })) + await user.click(screen.getByRole('button', { name: 'Requests' })) + await user.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false)) + expect(put).toHaveBeenCalledTimes(2) + expect(success).toHaveBeenCalledTimes(1) + expect(success).toHaveBeenCalledWith('Setting updated successfully') + }) + + it('keeps the dialog and the draft open when saving fails', async () => { + const put = mockApi({ 'model_square_setting.sort_mode': 'manual' }) + put.mockResolvedValueOnce({ data: { success: true } }) + put.mockResolvedValueOnce({ + data: { success: false, message: 'Invalid model square order setting' }, + }) + const success = vi.spyOn(toast, 'success') + const error = vi.spyOn(toast, 'error') + const onOpenChange = vi.fn() + const user = userEvent.setup() + renderDialog(onOpenChange) + + await user.click(await screen.findByRole('button', { name: 'Most used' })) + await user.click(screen.getByRole('button', { name: 'Requests' })) + await user.click(screen.getByRole('button', { name: 'Save' })) + + await waitFor(() => expect(error).toHaveBeenCalledTimes(1)) + expect(error).toHaveBeenCalledWith('Invalid model square order setting') + expect(success).not.toHaveBeenCalled() + expect(onOpenChange).not.toHaveBeenCalled() + expect(screen.getByRole('button', { name: 'Requests' })).toHaveAttribute( + 'aria-pressed', + 'true' + ) + }) + + it('discards the draft when the dialog is cancelled', async () => { + const put = mockApi({ 'model_square_setting.sort_mode': 'manual' }) + const onOpenChange = vi.fn() + const user = userEvent.setup() + const dialog = renderDialog(onOpenChange) + + await user.click(await screen.findByRole('button', { name: 'Most used' })) + expect(screen.getByRole('button', { name: 'Most used' })).toHaveAttribute( + 'aria-pressed', + 'true' + ) + await user.click(screen.getByRole('button', { name: 'Cancel' })) + expect(onOpenChange).toHaveBeenCalledWith(false) + dialog.rerender(false) + dialog.rerender(true) + + expect( + await screen.findByRole('button', { name: 'Manual order' }) + ).toHaveAttribute('aria-pressed', 'true') + expect(put).not.toHaveBeenCalled() + }) + + it('ranks the other models by the chosen metric after the pinned ones', async () => { + mockApi( + { + 'model_square_setting.sort_mode': 'mixed', + 'model_square_setting.sort_metric': 'tokens', + 'model_square_setting.sort_models': '["beta"]', + }, + { + gamma: { requests: 3, tokens: 9000 }, + alpha: { requests: 8, tokens: 100 }, + } + ) + const user = userEvent.setup() + renderDialog() + + const others = await screen.findByRole('list', { name: 'Other models' }) + const rows = () => within(others).getAllByRole('listitem') + expect(rows()).toHaveLength(2) + expect(rows()[0]).toHaveTextContent(/^2.*gamma.*9K$/) + expect(rows()[1]).toHaveTextContent(/^3.*alpha.*100$/) + + await user.click(screen.getByRole('button', { name: 'Requests' })) + + expect(rows()[0]).toHaveTextContent(/^2.*alpha.*8$/) + expect(rows()[1]).toHaveTextContent(/^3.*gamma.*3$/) + }) + + it('says the order falls back to names when there is no usage', async () => { + mockApi({ 'model_square_setting.sort_mode': 'usage' }) + renderDialog() + + expect( + await screen.findByText('No usage data, so models are ordered by name.') + ).toBeVisible() + }) +}) diff --git a/web/src/features/models/api.ts b/web/src/features/models/api.ts index 3d8c17d724..1d1876cc9a 100644 --- a/web/src/features/models/api.ts +++ b/web/src/features/models/api.ts @@ -30,6 +30,7 @@ import type { SyncUpstreamResponse, PreviewUpstreamDiffResponse, MissingModelsResponse, + ModelSquareUsageResponse, PrefillGroupsResponse, SyncLocale, SyncSource, @@ -240,6 +241,17 @@ export async function getMissingModels(): Promise { return res.data } +/** + * Get every model square model with its usage over the last days, for the + * model square order + */ +export async function getModelSquareUsage( + days: number +): Promise { + const res = await api.get('/api/models/square_usage', { params: { days } }) + return res.data +} + /** * Get prefill groups */ diff --git a/web/src/features/models/components/dialogs/model-square-order-dialog.tsx b/web/src/features/models/components/dialogs/model-square-order-dialog.tsx new file mode 100644 index 0000000000..447d76f9ab --- /dev/null +++ b/web/src/features/models/components/dialogs/model-square-order-dialog.tsx @@ -0,0 +1,450 @@ +/* +Copyright (C) 2023-2026 QuantumNous + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +For commercial licensing, please contact support@quantumnous.com +*/ +import { + keepPreviousData, + useMutation, + useQuery, + useQueryClient, +} from '@tanstack/react-query' +import { Reorder } from 'motion/react' +import { useMemo, useState, type ReactNode } from 'react' +import { useTranslation } from 'react-i18next' +import { toast } from 'sonner' + +import { AutoGroupOrderItem } from '@/components/auto-group-order-item' +import { Dialog } from '@/components/dialog' +import { Button } from '@/components/ui/button' +import { Combobox } from '@/components/ui/combobox' +import { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import { compareModelUsage } from '@/features/pricing/lib/filters' +import { updateSystemOption } from '@/features/system-settings/api' +import { + getOptionValue, + useSystemOptions, +} from '@/features/system-settings/hooks/use-system-options' +import type { UpdateOptionRequest } from '@/features/system-settings/types' +import { + SEGMENTED_SWITCH_CLASS, + SEGMENTED_SWITCH_ITEM_CLASS, +} from '@/features/task-plugins/components/plugin-kind-switch' +import { toIntlLocale } from '@/i18n/languages' +import { formatCompactNumber } from '@/lib/format' +import { handleServerError } from '@/lib/handle-server-error' +import { getLobeIcon } from '@/lib/lobe-icon' +import { requireServerSuccess } from '@/lib/server-error-message' + +import { getModelSquareUsage } from '../../api' +import { modelsQueryKeys } from '../../lib' +import type { ModelSquareUsage } from '../../types' + +const MODE_KEY = 'model_square_setting.sort_mode' +const METRIC_KEY = 'model_square_setting.sort_metric' +const DAYS_KEY = 'model_square_setting.sort_days' +const MODELS_KEY = 'model_square_setting.sort_models' + +// The saved settings; with no setting the square stays in name order. +const DEFAULT_ORDER = { + [MODE_KEY]: 'manual', + [METRIC_KEY]: 'tokens', + [DAYS_KEY]: 7, + [MODELS_KEY]: [] as string[], +} + +type OrderOptions = typeof DEFAULT_ORDER + +const PREVIEW_LIMIT = 10 + +function modelIcon(name: string, model?: ModelSquareUsage): ReactNode { + return getLobeIcon(model?.icon || model?.vendor_icon || name, 18) +} + +function ModelIconTile(props: { children: ReactNode }) { + return ( + + ) +} + +type ModelSquareOrderDialogProps = { + open: boolean + onOpenChange: (open: boolean) => void +} + +/** Lets the root admin choose the Recommended order of the model square. */ +export function ModelSquareOrderDialog(props: ModelSquareOrderDialogProps) { + const { t, i18n } = useTranslation() + const locale = toIntlLocale(i18n.resolvedLanguage || i18n.language) + const queryClient = useQueryClient() + const optionsQuery = useSystemOptions() + const [draft, setDraft] = useState(null) + + const saved = getOptionValue(optionsQuery.data?.data, DEFAULT_ORDER) + const order = draft ?? saved + const mode = order[MODE_KEY] + const metric = order[METRIC_KEY] + const days = order[DAYS_KEY] + const listed = order[MODELS_KEY] + const usesUsage = mode !== 'manual' + + // Every square model, whichever group can see it, with its usage + const usageQuery = useQuery({ + queryKey: modelsQueryKeys.squareUsage(days), + queryFn: async () => requireServerSuccess(await getModelSquareUsage(days)), + enabled: props.open, + placeholderData: keepPreviousData, + }) + const squareModels = useMemo( + () => usageQuery.data?.data ?? [], + [usageQuery.data] + ) + + const modelByName = useMemo( + () => new Map(squareModels.map((model) => [model.model_name, model])), + [squareModels] + ) + + const ranked = useMemo(() => { + const pinned = mode === 'mixed' ? listed : [] + return squareModels + .filter((model) => !pinned.includes(model.model_name)) + .map((model) => ({ + model, + name: model.model_name, + usage: metric === 'requests' ? model.requests : model.tokens, + })) + .sort(compareModelUsage) + }, [metric, mode, listed, squareModels]) + const hasUsage = ranked.some((row) => row.usage > 0) + + const update = (changes: Partial) => + setDraft({ ...order, ...changes }) + + const moveModel = (index: number, direction: 'up' | 'down') => { + const target = direction === 'up' ? index - 1 : index + 1 + if (target < 0 || target >= listed.length) return + const next = [...listed] + ;[next[index], next[target]] = [next[target], next[index]] + update({ [MODELS_KEY]: next }) + } + + const handleOpenChange = (open: boolean) => { + if (!open) setDraft(null) + props.onOpenChange(open) + } + + // One toast for the whole order, however many settings changed + const saveOrder = useMutation({ + mutationFn: async (changes: UpdateOptionRequest[]) => { + for (const change of changes) { + requireServerSuccess(await updateSystemOption(change)) + } + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['pricing'] }) + toast.success(t('Setting updated successfully')) + handleOpenChange(false) + }, + onError: (error) => handleServerError(error, t('Failed to update setting')), + onSettled: () => + queryClient.invalidateQueries({ queryKey: ['system-options'] }), + }) + + const handleSave = () => { + const keys = Object.keys(order) as (keyof OrderOptions)[] + saveOrder.mutate( + keys + .filter( + (key) => JSON.stringify(order[key]) !== JSON.stringify(saved[key]) + ) + .map((key) => { + const value = order[key] + return { + key, + value: Array.isArray(value) ? JSON.stringify(value) : value, + } + }) + ) + } + + const modes = [ + { value: 'manual', label: t('Manual order') }, + { value: 'usage', label: t('Most used') }, + { value: 'mixed', label: t('Pinned + most used') }, + ] + const periods = [ + { value: '1', label: t('Last 1 day') }, + { value: '7', label: t('Last 7 days') }, + { value: '30', label: t('Last 30 days') }, + ] + const metricLabel = metric === 'requests' ? t('Requests') : t('Tokens') + const addLabel = mode === 'mixed' ? t('Add pinned model') : t('Add model') + const candidates = squareModels + .filter((model) => !listed.includes(model.model_name)) + .map((model) => ({ + value: model.model_name, + label: model.model_name, + description: model.vendor_name, + icon: modelIcon(model.model_name, model), + })) + const previewRows = ranked.slice(0, PREVIEW_LIMIT) + const hiddenCount = ranked.length - previewRows.length + const rankOffset = mode === 'mixed' ? listed.length : 0 + + return ( + + + + + } + > +
+
+
{t('Sort method')}
+ { + const next = values.find((value) => value !== mode) + if (next) update({ [MODE_KEY]: next }) + }} + aria-label={t('Sort method')} + spacing={1} + className={SEGMENTED_SWITCH_CLASS} + > + {modes.map((item) => ( + + {item.label} + + ))} + +
+ + {usesUsage && ( +
+
+
{t('Rank by')}
+ { + const next = values.find((value) => value !== metric) + if (next) update({ [METRIC_KEY]: next }) + }} + variant='outline' + size='sm' + aria-label={t('Rank by')} + > + + {t('Requests')} + + {t('Tokens')} + +
+
+
{t('Period')}
+ +
+
+ )} + + {mode !== 'usage' && ( +
+
+
+ {mode === 'mixed' ? t('Pinned models') : t('Model order')} +
+ {listed.length > 1 && ( +
+ {t('Drag to reorder')} +
+ )} +
+ {listed.length > 0 && ( + update({ [MODELS_KEY]: next })} + className='flex flex-col gap-2' + > + {listed.map((name, index) => { + const model = modelByName.get(name) + return ( + {modelIcon(name, model)} + } + onMove={moveModel} + onRemove={(removed) => + update({ + [MODELS_KEY]: listed.filter( + (item) => item !== removed + ), + }) + } + > + {model?.vendor_name && ( + + {model.vendor_name} + + )} + + ) + })} + + )} + { + if (name && !listed.includes(name)) { + update({ [MODELS_KEY]: [...listed, name] }) + } + }} + placeholder={addLabel} + className='sm:w-72' + /> + {mode === 'manual' && ( +

+ {t('Models not in the list follow by name.')} +

+ )} +
+ )} + + {usesUsage && usageQuery.isSuccess && ( +
+
+
+ {mode === 'mixed' ? t('Other models') : t('Current order')} +
+ {hasUsage && ( +
+ {metricLabel} +
+ )} +
+ {!hasUsage && ( +

+ {t('No usage data, so models are ordered by name.')} +

+ )} + {hasUsage && ( +
    + {previewRows.map((row, index) => ( +
  1. + + {rankOffset + index + 1} + + + {modelIcon(row.model.model_name, row.model)} + +
    + + {row.model.model_name} + + {row.model.vendor_name && ( + + {row.model.vendor_name} + + )} +
    + + {formatCompactNumber(row.usage, locale)} + +
  2. + ))} +
+ )} + {hasUsage && hiddenCount > 0 && ( +

+ {t('And {{count}} more models', { count: hiddenCount })} +

+ )} +
+ )} +
+
+ ) +} diff --git a/web/src/features/models/components/models-dialogs.tsx b/web/src/features/models/components/models-dialogs.tsx index 6edc33720b..9e21b5c715 100644 --- a/web/src/features/models/components/models-dialogs.tsx +++ b/web/src/features/models/components/models-dialogs.tsx @@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com */ import { DescriptionDialog } from './dialogs/description-dialog' import { MissingModelsDialog } from './dialogs/missing-models-dialog' +import { ModelSquareOrderDialog } from './dialogs/model-square-order-dialog' import { PrefillGroupManagement } from './dialogs/prefill-group-management' import { PriceSyncDialog } from './dialogs/price-sync-dialog' import { SyncWizardDialog } from './dialogs/sync-wizard-dialog' @@ -73,6 +74,11 @@ export function ModelsDialogs() { onOpenChange={(v) => !v && setOpen(null)} /> + !v && setOpen(null)} + /> + {/* Prefill Groups Management */} state.auth.user?.role === ROLE.SUPER_ADMIN + ) const handleCreateModel = () => { setCurrentRow(null) @@ -68,6 +74,15 @@ export function ModelsPrimaryButtons() { {t('Sync pricing')} )} + {isRoot && ( + + )} {/* Create Model */}