Skip to content

fix: 未设置价格模型不会被拉取,除非设置自用模式 - #2222

Merged
Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
xyfacai:main
Nov 13, 2025
Merged

fix: 未设置价格模型不会被拉取,除非设置自用模式#2222
Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
xyfacai:main

Conversation

@xyfacai

@xyfacai xyfacai commented Nov 13, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features
    • Added model filtering based on pricing and ratio configuration settings. Only models with properly configured pricing information are now available when this setting is enabled.

@coderabbitai

coderabbitai Bot commented Nov 13, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces runtime gating for model listing based on user-specific ratio settings. A new function checks if models have configured ratios or prices, and model listing is filtered to exclude models without ratios when the user setting is disabled.

Changes

Cohort / File(s) Summary
Model listing gating
controller/model.go
Added runtime gating logic to filter models during listing based on ratio availability. Initializes acceptUnsetRatioModel from user settings and skips models without configured ratios when the flag is false.
Ratio/price lookup
setting/ratio_setting/model_ratio.go
Added GetModelRatioOrPrice(model string) function that attempts to fetch model price first, falls back to ratio, and returns default 37.5 if neither exists, with boolean flags indicating which value type was used and whether it exists.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ModelController
    participant UserSetting
    participant RatioSetting
    
    Client->>ModelController: ListModels()
    
    alt First call (acceptUnsetRatioModel unset)
        ModelController->>UserSetting: GetUserSetting()
        UserSetting-->>ModelController: AcceptUnsetRatioModel flag
        ModelController->>ModelController: Initialize acceptUnsetRatioModel
    end
    
    loop For each model in list
        alt acceptUnsetRatioModel is false
            ModelController->>RatioSetting: GetModelRatioOrPrice(model)
            RatioSetting-->>ModelController: ratio/price, exists flag
            
            alt Model has ratio/price
                ModelController->>ModelController: Include model
            else Model lacks ratio/price
                ModelController->>ModelController: Skip model
            end
        else acceptUnsetRatioModel is true
            ModelController->>ModelController: Include model
        end
    end
    
    ModelController-->>Client: Filtered model list
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Attention areas:
    • Logic in controller/model.go for gating application across multiple model source cohorts (token-based, grouped/user-specific) to ensure consistent filtering
    • Return value semantics and flag meanings in GetModelRatioOrPrice() to confirm correct interpretation (price vs. ratio, existence indicators)
    • Edge case handling when neither price nor ratio exists (default value of 37.5)

Possibly related PRs

Poem

🐰 A model's worth now checked with care,
Ratios and prices everywhere,
If none exist, we hop away,
Unless the user says "OK"!
Gating models, swift and fair,

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding runtime gating for model listing based on ratio/price settings and self-use mode configuration.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
controller/model.go (1)

135-140: Consider extracting the gating logic into a helper function.

The same gating logic appears in two places (lines 135-140 and 183-188). While the duplication is minimal, extracting it into a helper function would improve maintainability.

For example:

func shouldIncludeModel(modelName string, acceptUnsetRatioModel bool) bool {
	if acceptUnsetRatioModel {
		return true
	}
	_, _, exist := ratio_setting.GetModelRatioOrPrice(modelName)
	return exist
}

Then use it at both locations:

if !shouldIncludeModel(allowModel, acceptUnsetRatioModel) {
	continue
}

Also applies to: 183-188

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4419be9 and 06cd774.

📒 Files selected for processing (2)
  • controller/model.go (5 hunks)
  • setting/ratio_setting/model_ratio.go (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-05T17:14:17.246Z
Learnt from: neotf
Repo: QuantumNous/new-api PR: 1511
File: setting/ratio_setting/model_ratio.go:118-123
Timestamp: 2025-08-05T17:14:17.246Z
Learning: Claude models handle "-thinking" variants differently from Gemini models. For Claude models, only the base model (without "-thinking") gets an entry in defaultModelRatio map. The "-thinking" variants rely on the Claude relay handler stripping the suffix using strings.TrimSuffix(textRequest.Model, "-thinking") before looking up the ratio, so they automatically use the base model's ratio.

Applied to files:

  • setting/ratio_setting/model_ratio.go
  • controller/model.go
🧬 Code graph analysis (1)
controller/model.go (3)
setting/operation_setting/operation_setting.go (1)
  • SelfUseModeEnabled (6-6)
model/user.go (1)
  • GetUserSetting (723-751)
setting/ratio_setting/model_ratio.go (1)
  • GetModelRatioOrPrice (828-838)
🔇 Additional comments (2)
setting/ratio_setting/model_ratio.go (1)

827-838: LGTM! Function correctly implements price/ratio lookup with existence flag.

The function provides a clean way to check if a model has a configured price or ratio, which is used for gating model availability in the listing endpoint.

controller/model.go (1)

114-123: Implementation correctly gates models based on ratio/price configuration.

The gating logic aligns with the PR objective: models without configured ratios or prices are now excluded from listing unless self-use mode is enabled globally or per-user. The implementation correctly:

  1. Checks global SelfUseModeEnabled first
  2. Falls back to per-user AcceptUnsetRatioModel setting
  3. Applies consistent gating in both token-based and group-based model listing paths

Also applies to: 135-140, 183-188

Comment thread controller/model.go
Comment on lines +114 to +123
acceptUnsetRatioModel := operation_setting.SelfUseModeEnabled
if !acceptUnsetRatioModel {
userId := c.GetInt("id")
if userId > 0 {
userSettings, _ := model.GetUserSetting(userId, false)
if userSettings.AcceptUnsetRatioModel {
acceptUnsetRatioModel = true
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Consider logging the error from GetUserSetting.

The error from GetUserSetting is currently ignored. While the default behavior (treating as AcceptUnsetRatioModel=false) is safe, logging the error would help with debugging user setting retrieval issues.

Apply this diff to log the error:

 	if !acceptUnsetRatioModel {
 		userId := c.GetInt("id")
 		if userId > 0 {
-			userSettings, _ := model.GetUserSetting(userId, false)
+			userSettings, err := model.GetUserSetting(userId, false)
+			if err != nil {
+				common.SysLog(fmt.Sprintf("failed to get user setting for user %d: %v", userId, err))
+			}
 			if userSettings.AcceptUnsetRatioModel {
 				acceptUnsetRatioModel = true
 			}
🤖 Prompt for AI Agents
In controller/model.go around lines 114 to 123, the call to model.GetUserSetting
ignores its error; update the code to capture the returned error, and if non-nil
log it with context (including the userId) before continuing with the safe
default. Specifically, change the assignment to userSettings, err :=
model.GetUserSetting(userId, false), then if err != nil call the request/logger
(e.g. c.Logger.Errorf or the project’s logger) to record a clear message and the
error value, and only set acceptUnsetRatioModel if err == nil and
userSettings.AcceptUnsetRatioModel is true.

@Calcium-Ion
Calcium-Ion merged commit 974df5e into QuantumNous:main Nov 13, 2025
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Dec 23, 2025
Closed
5 tasks
ennnnny pushed a commit to ennnnny/new-api that referenced this pull request Mar 17, 2026
fix: 未设置价格模型不会被拉取,除非设置自用模式
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants