-
Notifications
You must be signed in to change notification settings - Fork 11.1k
fix: include tiered billing models in model listing #4431
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Calcium-Ion
merged 1 commit into
QuantumNous:main
from
yyhhyyyyyy:fix/tiered-billing-model-list
Apr 24, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,242 @@ | ||
| package controller | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "os" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/QuantumNous/new-api/common" | ||
| "github.com/QuantumNous/new-api/constant" | ||
| "github.com/QuantumNous/new-api/dto" | ||
| "github.com/QuantumNous/new-api/model" | ||
| "github.com/QuantumNous/new-api/setting/config" | ||
| "github.com/QuantumNous/new-api/setting/operation_setting" | ||
| "github.com/gin-gonic/gin" | ||
| "github.com/glebarez/sqlite" | ||
| "github.com/stretchr/testify/require" | ||
| "gorm.io/gorm" | ||
| ) | ||
|
|
||
| type listModelsResponse struct { | ||
| Success bool `json:"success"` | ||
| Data []dto.OpenAIModels `json:"data"` | ||
| Object string `json:"object"` | ||
| } | ||
|
|
||
| func setupModelListControllerTestDB(t *testing.T) *gorm.DB { | ||
| t.Helper() | ||
|
|
||
| initModelListColumnNames(t) | ||
|
|
||
| gin.SetMode(gin.TestMode) | ||
| common.UsingSQLite = true | ||
| common.UsingMySQL = false | ||
| common.UsingPostgreSQL = false | ||
| common.RedisEnabled = false | ||
|
|
||
| dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", strings.ReplaceAll(t.Name(), "/", "_")) | ||
| db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{}) | ||
| require.NoError(t, err) | ||
| model.DB = db | ||
| model.LOG_DB = db | ||
|
|
||
| require.NoError(t, db.AutoMigrate(&model.User{}, &model.Channel{}, &model.Ability{}, &model.Model{}, &model.Vendor{})) | ||
|
|
||
| t.Cleanup(func() { | ||
| sqlDB, err := db.DB() | ||
| if err == nil { | ||
| _ = sqlDB.Close() | ||
| } | ||
| }) | ||
|
|
||
| return db | ||
| } | ||
|
|
||
| func initModelListColumnNames(t *testing.T) { | ||
| t.Helper() | ||
|
|
||
| originalIsMasterNode := common.IsMasterNode | ||
| originalSQLitePath := common.SQLitePath | ||
| originalUsingSQLite := common.UsingSQLite | ||
| originalUsingMySQL := common.UsingMySQL | ||
| originalUsingPostgreSQL := common.UsingPostgreSQL | ||
| originalSQLDSN, hadSQLDSN := os.LookupEnv("SQL_DSN") | ||
| defer func() { | ||
| common.IsMasterNode = originalIsMasterNode | ||
| common.SQLitePath = originalSQLitePath | ||
| common.UsingSQLite = originalUsingSQLite | ||
| common.UsingMySQL = originalUsingMySQL | ||
| common.UsingPostgreSQL = originalUsingPostgreSQL | ||
| if hadSQLDSN { | ||
| require.NoError(t, os.Setenv("SQL_DSN", originalSQLDSN)) | ||
| } else { | ||
| require.NoError(t, os.Unsetenv("SQL_DSN")) | ||
| } | ||
| }() | ||
|
|
||
| common.IsMasterNode = false | ||
| common.SQLitePath = fmt.Sprintf("file:%s_init?mode=memory&cache=shared", strings.ReplaceAll(t.Name(), "/", "_")) | ||
| common.UsingSQLite = false | ||
| common.UsingMySQL = false | ||
| common.UsingPostgreSQL = false | ||
| require.NoError(t, os.Setenv("SQL_DSN", "local")) | ||
|
|
||
| require.NoError(t, model.InitDB()) | ||
| if model.DB != nil { | ||
| sqlDB, err := model.DB.DB() | ||
| if err == nil { | ||
| _ = sqlDB.Close() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func withTieredBillingConfig(t *testing.T, modes map[string]string, exprs map[string]string) { | ||
| t.Helper() | ||
|
|
||
| saved := map[string]string{} | ||
| require.NoError(t, config.GlobalConfig.SaveToDB(func(key, value string) error { | ||
| if strings.HasPrefix(key, "billing_setting.") { | ||
| saved[key] = value | ||
| } | ||
| return nil | ||
| })) | ||
| t.Cleanup(func() { | ||
| require.NoError(t, config.GlobalConfig.LoadFromDB(saved)) | ||
| model.InvalidatePricingCache() | ||
| }) | ||
|
|
||
| modeBytes, err := common.Marshal(modes) | ||
| require.NoError(t, err) | ||
| exprBytes, err := common.Marshal(exprs) | ||
| require.NoError(t, err) | ||
|
|
||
| require.NoError(t, config.GlobalConfig.LoadFromDB(map[string]string{ | ||
| "billing_setting.billing_mode": string(modeBytes), | ||
| "billing_setting.billing_expr": string(exprBytes), | ||
| })) | ||
| model.InvalidatePricingCache() | ||
| } | ||
|
|
||
| func withSelfUseModeDisabled(t *testing.T) { | ||
| t.Helper() | ||
|
|
||
| original := operation_setting.SelfUseModeEnabled | ||
| operation_setting.SelfUseModeEnabled = false | ||
| t.Cleanup(func() { | ||
| operation_setting.SelfUseModeEnabled = original | ||
| }) | ||
| } | ||
|
|
||
| func decodeListModelsResponse(t *testing.T, recorder *httptest.ResponseRecorder) map[string]struct{} { | ||
| t.Helper() | ||
|
|
||
| require.Equal(t, http.StatusOK, recorder.Code) | ||
| var payload listModelsResponse | ||
| require.NoError(t, common.Unmarshal(recorder.Body.Bytes(), &payload)) | ||
| require.True(t, payload.Success) | ||
| require.Equal(t, "list", payload.Object) | ||
|
|
||
| ids := make(map[string]struct{}, len(payload.Data)) | ||
| for _, item := range payload.Data { | ||
| ids[item.Id] = struct{}{} | ||
| } | ||
| return ids | ||
| } | ||
|
|
||
| func pricingByModelName(pricings []model.Pricing) map[string]model.Pricing { | ||
| byName := make(map[string]model.Pricing, len(pricings)) | ||
| for _, pricing := range pricings { | ||
| byName[pricing.ModelName] = pricing | ||
| } | ||
| return byName | ||
| } | ||
|
|
||
| func TestListModelsIncludesTieredBillingModel(t *testing.T) { | ||
| withSelfUseModeDisabled(t) | ||
| withTieredBillingConfig(t, map[string]string{ | ||
| "zz-tiered-visible-model": "tiered_expr", | ||
| "zz-tiered-empty-expr-model": "tiered_expr", | ||
| "zz-tiered-missing-expr-model": "tiered_expr", | ||
| }, map[string]string{ | ||
| "zz-tiered-visible-model": `tier("base", p * 1 + c * 2)`, | ||
| "zz-tiered-empty-expr-model": " ", | ||
| }) | ||
|
|
||
| db := setupModelListControllerTestDB(t) | ||
| require.NoError(t, db.Create(&model.User{ | ||
| Id: 1001, | ||
| Username: "model-list-user", | ||
| Password: "password", | ||
| Group: "default", | ||
| Status: common.UserStatusEnabled, | ||
| }).Error) | ||
| require.NoError(t, db.Create(&[]model.Ability{ | ||
| {Group: "default", Model: "zz-tiered-visible-model", ChannelId: 1, Enabled: true}, | ||
| {Group: "default", Model: "zz-tiered-empty-expr-model", ChannelId: 1, Enabled: true}, | ||
| {Group: "default", Model: "zz-tiered-missing-expr-model", ChannelId: 1, Enabled: true}, | ||
| {Group: "default", Model: "zz-unpriced-model", ChannelId: 1, Enabled: true}, | ||
| }).Error) | ||
|
|
||
| recorder := httptest.NewRecorder() | ||
| ctx, _ := gin.CreateTestContext(recorder) | ||
| ctx.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) | ||
| ctx.Set("id", 1001) | ||
|
|
||
| ListModels(ctx, constant.ChannelTypeOpenAI) | ||
|
|
||
| ids := decodeListModelsResponse(t, recorder) | ||
| require.Contains(t, ids, "zz-tiered-visible-model") | ||
| require.NotContains(t, ids, "zz-tiered-empty-expr-model") | ||
| require.NotContains(t, ids, "zz-tiered-missing-expr-model") | ||
| require.NotContains(t, ids, "zz-unpriced-model") | ||
|
|
||
| pricingByName := pricingByModelName(model.GetPricing()) | ||
| visiblePricing, ok := pricingByName["zz-tiered-visible-model"] | ||
| require.True(t, ok) | ||
| require.Equal(t, "tiered_expr", visiblePricing.BillingMode) | ||
| require.NotEmpty(t, visiblePricing.BillingExpr) | ||
|
|
||
| emptyExprPricing, ok := pricingByName["zz-tiered-empty-expr-model"] | ||
| require.True(t, ok) | ||
| require.Empty(t, emptyExprPricing.BillingMode) | ||
| require.Empty(t, emptyExprPricing.BillingExpr) | ||
|
|
||
| missingExprPricing, ok := pricingByName["zz-tiered-missing-expr-model"] | ||
| require.True(t, ok) | ||
| require.Empty(t, missingExprPricing.BillingMode) | ||
| require.Empty(t, missingExprPricing.BillingExpr) | ||
| } | ||
|
|
||
| func TestListModelsTokenLimitIncludesTieredBillingModel(t *testing.T) { | ||
| withSelfUseModeDisabled(t) | ||
| withTieredBillingConfig(t, map[string]string{ | ||
| "zz-token-tiered-visible-model": "tiered_expr", | ||
| "zz-token-tiered-empty-expr-model": "tiered_expr", | ||
| "zz-token-tiered-missing-expr-model": "tiered_expr", | ||
| }, map[string]string{ | ||
| "zz-token-tiered-visible-model": `tier("base", p * 1 + c * 2)`, | ||
| "zz-token-tiered-empty-expr-model": "", | ||
| }) | ||
|
|
||
| recorder := httptest.NewRecorder() | ||
| ctx, _ := gin.CreateTestContext(recorder) | ||
| ctx.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) | ||
| common.SetContextKey(ctx, constant.ContextKeyTokenModelLimitEnabled, true) | ||
| common.SetContextKey(ctx, constant.ContextKeyTokenModelLimit, map[string]bool{ | ||
| "zz-token-tiered-visible-model": true, | ||
| "zz-token-tiered-empty-expr-model": true, | ||
| "zz-token-tiered-missing-expr-model": true, | ||
| "zz-token-unpriced-model": true, | ||
| }) | ||
|
|
||
| ListModels(ctx, constant.ChannelTypeOpenAI) | ||
|
|
||
| ids := decodeListModelsResponse(t, recorder) | ||
| require.Contains(t, ids, "zz-token-tiered-visible-model") | ||
| require.NotContains(t, ids, "zz-token-tiered-empty-expr-model") | ||
| require.NotContains(t, ids, "zz-token-tiered-missing-expr-model") | ||
| require.NotContains(t, ids, "zz-token-unpriced-model") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Stale reads from dependent caches between invalidation and next refresh.
InvalidatePricingCacheonly clearspricingMap,vendorsList, andlastGetPricingTime, but leaves the related caches populated byupdatePricing:modelSupportEndpointTypes,supportedEndpointMap,modelEnableGroups, andmodelQuotaTypeMap. Callers that read these maps directly (e.g.,GetModelSupportEndpointTypes,GetSupportedEndpointMap) will continue to return pre-invalidation data until the nextGetPricing()call triggers a rebuild.For a
billing_settingupdate this is probably fine (the affected fields areBillingMode/BillingExpron pricing entries, which do get refreshed viapricingMap=nil), but if this helper is ever reused for a wider config change, the behavior could surprise. Consider either documenting the scope or also nilling the dependent maps under their respective locks.🤖 Prompt for AI Agents