Skip to content

feat(Gemini): implement thinking budget control in model name - #1231

Merged
Calcium-Ion merged 3 commits into
QuantumNous:alphafrom
RedwindA:feat/gemini-budget-in-name
Jun 16, 2025
Merged

Calcium-Ion merged 3 commits into
QuantumNous:alphafrom
RedwindA:feat/gemini-budget-in-name

Conversation

@RedwindA

@RedwindA RedwindA commented Jun 15, 2025 •

Copy link
Copy Markdown
Contributor

close #1183

  • 通过gemini-2.5-pro-preview-06-05-thinking-128这种模型名格式控制思考预算,旧的比例规则仍然有效;
  • 配置了默认倍率以及类似gizmo的通配符处理,方便自定义;
  • 更新了设置界面的说明文本与i18n。

Summary by CodeRabbit

  • New Features
    • Added support for Gemini model names with thinking budget parameters, enabling more precise control over thinking budgets.
    • Extended model ratio settings to handle new Gemini 2.5 flash and pro thinking budget models using wildcard entries for unified pricing.
  • Improvements
    • Updated interface and localization text to clarify support for new Gemini model naming formats and thinking budget configuration.
  • Bug Fixes
    • Enhanced model name normalization to support additional suffix patterns for better compatibility.

@coderabbitai

coderabbitai Bot commented Jun 15, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

The updates introduce support for Gemini model names that include a thinking budget parameter (e.g., "-thinking-128"), enhancing normalization and processing logic to recognize and handle these new naming conventions. Associated configuration, pricing ratio logic, and UI text are updated to reflect and support these changes, including new localization entries.

Changes

Files/Groups Change Summary
relay/channel/gemini/adaptor.go Enhanced model name normalization in GetRequestURL to handle "-thinking-" anywhere in the model name, supporting new budgeted thinking suffixes.
relay/channel/gemini/relay-gemini.go Added parsing and handling for "-thinking-" in model names, extracting and validating budget values, and updating thinking configuration logic accordingly.
setting/operation_setting/model-ratio.go Expanded model ratio logic with wildcard keys for budgeted thinking models, generalized prefix matching, and added new entries for recent Gemini 2.5 flash preview variants.
web/src/i18n/locales/en.json Added six new English localization strings related to Gemini thinking suffix adaptation and thinking budget ratio settings.
web/src/pages/Setting/Model/SettingGeminiModel.js Updated UI text to clarify and support new thinking budget suffixes, including more precise descriptions and revised labels for Gemini model thinking adaptation settings.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI
    participant Backend
    participant GeminiAdaptor
    participant GeminiRelay

    User->>UI: Selects Gemini model with "-thinking-<budget>" suffix
    UI->>Backend: Sends model selection and config
    Backend->>GeminiAdaptor: Normalizes model name (handles "-thinking-<budget>")
    GeminiAdaptor->>GeminiRelay: Passes normalized name and config
    GeminiRelay->>GeminiRelay: Parses budget from name, validates, sets config
    GeminiRelay->>Backend: Returns processed config
    Backend->>UI: Updates with new settings/ratios
    UI->>User: Displays updated settings and descriptions
Loading

Assessment against linked issues

Objective Addressed Explanation
Set thinking budget to 128 tokens when "-nothinking" suffix is passed for new Gemini 2.5 pro models (#1183) ✅ The code sets a minimum thinking budget of 128 tokens for 2.5 pro models with "-nothinking" suffix.

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected.

Poem

In the warren of code, a suffix appears,
"-thinking-128" hops in, the logic now clears.
Budgets for bunnies, so clever and neat,
Ratios and settings, all hop to the beat.
With new words and labels, our UI will sing—
Gemini’s thoughts now have room for their spring!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c48a398 and 1294d28.

📒 Files selected for processing (1)
  • setting/operation_setting/model-ratio.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • setting/operation_setting/model-ratio.go
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@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: 0

🧹 Nitpick comments (3)
relay/channel/gemini/adaptor.go (1)

72-84: Edge-cases in -thinking- stripping logic

  1. strings.Split(info.UpstreamModelName, "-thinking-") will always allocate the whole slice, yet you only need the prefix.
  2. When info.OriginModelName does contain “-thinking-” but info.UpstreamModelName doesn’t (e.g. they were already normalised upstream), parts will have length 1 → you silently keep the original value; that’s fine but the extra allocation is wasted.
  3. A simpler (& allocation-free) pattern is:
- if strings.Contains(info.OriginModelName, "-thinking-") {
-     parts := strings.Split(info.UpstreamModelName, "-thinking-")
-     info.UpstreamModelName = parts[0]
+ if idx := strings.Index(info.UpstreamModelName, "-thinking-"); idx != -1 {
+     info.UpstreamModelName = info.UpstreamModelName[:idx]
 }

This avoids the intermediate slice and guards directly on the real string you mutate.

Minor, but worth it in a hot path that runs on every request.

relay/channel/gemini/relay-gemini.go (1)

67-101: Parsing logic works but is brittle; consider a tiny refactor

‐ strings.SplitN() plus strconv.Atoi succeeds only when the token right after “-thinking-” is a pure decimal string. Any trailing text (e.g. version suffix) silently disables thinking support because Atoi fails.
‐ The isNew25Pro check is duplicated three times in this file; extracting it into a small helper would cut repetition and future-proof the range rules.

Optional compact refactor:

+var new25ProRegexp = regexp.MustCompile(`^gemini-2\.5-pro(?!-preview-(05-06|03-25))`)
+
+func parseThinkingBudget(model string) (int, bool) {
+    m := thinkingBudgetRegexp.FindStringSubmatch(model) // e.g. []{"-thinking-128","128"}
+    if len(m) != 2 { return 0, false }
+    budget, err := strconv.Atoi(m[1])
+    if err != nil { return 0, false }
+    if new25ProRegexp.MatchString(model) {
+        return clamp(budget, pro25MinBudget, pro25MaxBudget), true
+    }
+    return clamp(budget, 0, flash25MaxBudget), true
+}

This reduces edge-case fragility and centralises the clamping logic.

🧰 Tools
🪛 Gitleaks (8.26.0)

81-81: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


82-82: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


83-83: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

setting/operation_setting/model-ratio.go (1)

353-361: Inline closure mutates outer variable – readability concern

handleThinkingBudgetModel closes over and mutates name. While correct, it costs a mental round-trip for readers (captured-by-reference semantics). A straight if chain is clearer and avoids needless reassignments under a read lock:

-	handleThinkingBudgetModel := func(prefix, wildcard string) {
-		if strings.HasPrefix(name, prefix) && strings.Contains(name, "-thinking-") {
-			name = wildcard
-		}
-	}
-	handleThinkingBudgetModel("gemini-2.5-flash", "gemini-2.5-flash-thinking-*")
-	handleThinkingBudgetModel("gemini-2.5-pro", "gemini-2.5-pro-thinking-*")
+	if strings.HasPrefix(name, "gemini-2.5-flash") && strings.Contains(name, "-thinking-") {
+		name = "gemini-2.5-flash-thinking-*"
+	} else if strings.HasPrefix(name, "gemini-2.5-pro") && strings.Contains(name, "-thinking-") {
+		name = "gemini-2.5-pro-thinking-*"
+	}

Purely stylistic, but it improves traceability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d2b4796 and e735377.

📒 Files selected for processing (5)
  • relay/channel/gemini/adaptor.go (1 hunks)
  • relay/channel/gemini/relay-gemini.go (3 hunks)
  • setting/operation_setting/model-ratio.go (3 hunks)
  • web/src/i18n/locales/en.json (1 hunks)
  • web/src/pages/Setting/Model/SettingGeminiModel.js (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
relay/channel/gemini/relay-gemini.go (2)
relay/channel/gemini/dto.go (1)
  • GeminiThinkingConfig (13-16)
common/utils.go (1)
  • GetPointer (217-219)
🪛 Gitleaks (8.26.0)
relay/channel/gemini/relay-gemini.go

81-81: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


82-82: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


83-83: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (7)
web/src/pages/Setting/Model/SettingGeminiModel.js (3)

174-178: Missing i18n entry for the updated long description

The Chinese literal passed to t() has changed, but no corresponding key/value was added to en.json.
Result: English UI will now fall back to Chinese for this paragraph.

Add the new sentence (full Chinese string) to web/src/i18n/locales/en.json to keep localisation complete.


186-188: 👍 Extra helper text clearly explains supported suffixes

The new extraText precisely lists all accepted patterns, improving UX.


208-215: Label & validator are in sync

The label change to “思考预算占比” together with the 0.1–1 range keeps validation coherent with backend expectations.

web/src/i18n/locales/en.json (1)

1375-1378: New translations look consistent

Keys follow the existing “Chinese-key → English-value” convention and wording matches UI labels.

relay/channel/gemini/relay-gemini.go (1)

40-45: Constants clarify magic numbers—👍

Introducing named constants for the various budget limits removes “magic numbers” that previously appeared multiple times in the code. This is a clear readability / maintainability win.

setting/operation_setting/model-ratio.go (2)

145-149: Good forward-compat defaults

Adding wildcard keys for thinking variants will stop pricing gaps as new budgets appear. Looks solid.


485-493: Ratio rule generalisation is clear

Relaxing the preview-only check ensures official (non-preview) 2.5 models inherit the intended ratio—nice catch.

@Calcium-Ion
Calcium-Ion merged commit 246ca40 into QuantumNous:alpha Jun 16, 2025
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
…in-name

feat(Gemini): implement thinking budget control in model name
jiutubaba pushed a commit to jiutubaba/fx-api that referenced this pull request May 17, 2026
…ugh-worktree

Support bulk editing for OpenAI passthrough
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
…in-name

feat(Gemini): implement thinking budget control in model name
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
…in-name

feat(Gemini): implement thinking budget control in model name
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