Skip to content

feat: add thinking summaries option for gemini - #1273

Closed
9Ninety wants to merge 1 commit into
QuantumNous:alphafrom
9Ninety:main
Closed

feat: add thinking summaries option for gemini#1273
9Ninety wants to merge 1 commit into
QuantumNous:alphafrom
9Ninety:main

Conversation

@9Ninety

@9Ninety 9Ninety commented Jun 21, 2025

Copy link
Copy Markdown
Contributor

This pull request decouples the thoughts summary feature from the thinking budget mechanism. The primary goal is to provide users with greater flexibility by treating these as two independent settings, which aligns with their underlying design.

The Problem

Previously, enabling the thoughts summary was tightly coupled with the thinking budget. This created a situation where users who wanted a summary were forced to use the -thinking suffix.

This forced coupling becomes problematic when a user wants to see the thinking summary and the client also passes a max_completion_tokens value. The -thinking suffix would then also trigger its specific thinking budget behavior. This meant the model's default, automatic thinking budget behavior would be overridden in favozr of a calculated value.

This approach limited flexibility, as it was impossible to request a summary while ensuring the default thinking budget strategy remained untouched.

The Solution

This PR introduces an independent toggle for the thoughts summary. The implementation details are as follows:

  • New Setting: A new IncludeThoughtsSummaryEnabled setting is added. It is only active when the main ThinkingAdapterEnabled feature is also turned on. If the adapter is disabled, there is no change in behavior.
  • Default Behavior: When the adapter is enabled, users will receive a thoughts summary by default with standard model names (without needing the -thinking suffix). They can explicitly disable this by turning the new toggle off.

By decoupling these two features, users can get a thinking summary without using the suffix. This ensures that unless the user explicitly chooses the -thinking suffix, the thinking budget is not interfered with, aligning the behavior with Google's official automatic thinking strategy.

A Note on Models with Minimum Thinking Budgets

For models with a minimum thinking budget limit (like gemini-2.5-pro), includeThoughts is still sent when the summary toggle is on, even if the -nothinking suffix is used. This is by design and aligns with Google's official API behavior, reflecting that these models' thinking processes cannot be fully disabled. The summary is returned in the dedicated reasoning_content field and does not affect response compatibility.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Added a setting to enable or disable inclusion of a "thoughts summary" in Gemini model replies, accessible in the Gemini model settings UI.
    • Introduced a switch control in the settings interface to toggle this feature, with clear labels and descriptions.
    • Enhanced thinking budget handling for Gemini models with refined controls based on model capabilities and suffixes.
  • Localization
    • Added English translations for the new "Include thinking summaries" option and its description in the settings.

@coderabbitai

coderabbitai Bot commented Jun 21, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change introduces support for configuring and applying a "thoughts summary" feature for Gemini models. It adds new constants, helper functions, and UI controls to manage whether a summary of the model's thought process is included in responses, depending on model capabilities and user settings. The thinking budget handling logic in relay-gemini.go is refactored for clarity and separation of concerns.

Changes

File(s) Change Summary
relay/channel/gemini/constant.go Added two exported string slices listing Gemini models with thoughts summary support and minimum thinking limits.
relay/channel/gemini/helper.go Introduced helper functions to check if a model supports thoughts summary or has minimum thinking budget limits.
relay/channel/gemini/relay-gemini.go Refactored ThinkingAdaptor to clarify thinking budget logic and separate thoughts summary inclusion handling.
setting/model_setting/gemini.go Added IncludeThoughtsSummaryEnabled boolean field to GeminiSettings, defaulting to true.
web/src/components/settings/ModelSetting.js Added 'gemini.include_thoughts_summary_enabled' key with default true to state initialization.
web/src/i18n/locales/en.json Added English localization strings for thoughts summary setting and description.
web/src/pages/Setting/Model/SettingGeminiModel.js Added switch UI for thoughts summary inclusion; updated state initialization for the new setting.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI
    participant Server
    participant Gemini

    User->>UI: Toggle "Include thoughts summary" setting
    UI->>Server: Save updated Gemini settings
    User->>UI: Submit chat request
    UI->>Server: Send chat request with model name and settings
    Server->>Server: ApplyThinkingAdaptationSettings(request, modelName)
    Server->>Gemini: Forward request with thinking budget and thoughts summary config
    Gemini-->>Server: Respond with (optional) thoughts summary
    Server-->>UI: Return response (with/without thoughts summary)
    UI-->>User: Display reply (with/without thoughts summary)
Loading

Possibly related PRs

  • QuantumNous/new-api#1231: Implements initial parsing and handling of thinking budget suffixes in model names, extending logic in relay-gemini.go; both PRs overlap in thinking budget processing for Gemini models.
  • QuantumNous/new-api#1271: Adds handling for "-thinking-" suffix trimming and thinking budget parsing, related to the thinking budget logic refined here.
  • QuantumNous/new-api#1247: Refines thinking budget handling for Gemini models, complements this PR by centralizing budget clamping logic.

Poem

A bunny hopped through Gemini's code,
With thoughts summary now in tow,
Flipping a switch, so users can pick,
Whether to see how the models think quick.
Settings aligned, UI refined—
Now Gemini’s mind is easier to find!
🐇✨


📜 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 31a6141 and 0e9a0a8.

📒 Files selected for processing (7)
  • relay/channel/gemini/constant.go (1 hunks)
  • relay/channel/gemini/helper.go (1 hunks)
  • relay/channel/gemini/relay-gemini.go (1 hunks)
  • setting/model_setting/gemini.go (2 hunks)
  • web/src/components/settings/ModelSetting.js (1 hunks)
  • web/src/i18n/locales/en.json (1 hunks)
  • web/src/pages/Setting/Model/SettingGeminiModel.js (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • relay/channel/gemini/helper.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • web/src/components/settings/ModelSetting.js
  • setting/model_setting/gemini.go
  • web/src/i18n/locales/en.json
  • web/src/pages/Setting/Model/SettingGeminiModel.js
  • relay/channel/gemini/constant.go
  • relay/channel/gemini/relay-gemini.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: 1

🧹 Nitpick comments (2)
relay/channel/gemini/helper.go (1)

1-26: Consider adding performance optimization for frequent calls.

Since these functions may be called frequently during request processing, consider caching results or using a more efficient lookup mechanism like a map-based approach for better performance.

Here's an optimized version using map lookups:

+var (
+	thoughtsSummSupportCache = make(map[string]bool)
+	minThinkingBudgetCache = make(map[string]bool)
+)
+
+func buildCache() {
+	for _, model := range ModelsWithThoughtsSummarySupport {
+		thoughtsSummSupportCache[model] = true
+	}
+	for _, model := range ModelsWithMinimumThinkingBudgetLimits {
+		minThinkingBudgetCache[model] = true
+	}
+}

 func IsModelSupportThoughtsSummary(modelName string) bool {
+	// Direct lookup first
+	if supported, exists := thoughtsSummSupportCache[modelName]; exists {
+		return supported
+	}
+	
+	// Fall back to prefix matching
 	for _, supportedModel := range ModelsWithThoughtsSummarySupport {
 		if strings.HasPrefix(modelName, supportedModel) {
+			thoughtsSummSupportCache[modelName] = true
 			return true
 		}
 	}
+	thoughtsSummSupportCache[modelName] = false
 	return false
 }
relay/channel/gemini/relay-gemini.go (1)

131-131: Consider adding null check for better robustness.

While unlikely, consider adding a null check for the Gemini settings to prevent potential panics.

-if model_setting.GetGeminiSettings().IncludeThoughtsSummaryEnabled && IsModelSupportThoughtsSummary(modelName) {
+geminiSettings := model_setting.GetGeminiSettings()
+if geminiSettings != nil && geminiSettings.IncludeThoughtsSummaryEnabled && IsModelSupportThoughtsSummary(modelName) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 59574dc and b91a612.

📒 Files selected for processing (7)
  • relay/channel/gemini/constant.go (1 hunks)
  • relay/channel/gemini/helper.go (1 hunks)
  • relay/channel/gemini/relay-gemini.go (2 hunks)
  • setting/model_setting/gemini.go (2 hunks)
  • web/src/components/settings/ModelSetting.js (1 hunks)
  • web/src/i18n/locales/en.json (1 hunks)
  • web/src/pages/Setting/Model/SettingGeminiModel.js (2 hunks)
🔇 Additional comments (15)
setting/model_setting/gemini.go (2)

14-14: LGTM! Field addition follows established patterns.

The new IncludeThoughtsSummaryEnabled field is properly positioned, follows naming conventions, and includes the correct JSON tag.


33-33: LGTM! Default value is consistent with frontend.

The default value of true matches the frontend implementation and makes sense for user experience - users get thoughts summaries by default when the adapter is enabled.

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

29-41: LGTM! Well-documented model capability constants.

The new constants are properly named, well-documented with clear comments, and include a helpful reference URL. The model lists are logically organized with Gemini 2.5 series models, which aligns with their advanced thinking capabilities.

web/src/components/settings/ModelSetting.js (1)

25-25: LGTM! Default setting follows established pattern.

The new setting key follows the existing naming convention and is positioned logically with other Gemini settings. The default value of true is consistent with the backend configuration.

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

1692-1693: LGTM! Clear and informative localization strings.

The English translations are clear and accurately describe the feature functionality. The explanatory text properly communicates the conditions under which the feature is effective (model support and non-zero thinking budget).

web/src/pages/Setting/Model/SettingGeminiModel.js (2)

33-33: LGTM! Initial state value is consistent.

The default value matches the backend configuration and other frontend settings, ensuring consistency across the application.


225-239: LGTM! UI component follows established patterns.

The new Form.Switch component is properly implemented following the same pattern as existing switches. It includes:

  • Correct field binding to match backend setting
  • Proper localized labels and explanatory text
  • Appropriate onChange handler that updates state
  • Logical placement within the thinking adaptation section

The implementation is consistent with the rest of the codebase.

relay/channel/gemini/helper.go (2)

7-15: Function logic is correct and well-implemented.

The function correctly iterates through supported models and uses prefix matching to determine compatibility. The early return pattern is efficient.


17-25: Function logic is correct and mirrors the pattern above.

The function follows the same efficient pattern as IsModelSupportThoughtsSummary, ensuring consistency in the codebase.

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

81-84: Good early return pattern for disabled feature.

The early return when ThinkingAdapterEnabled is false is efficient and prevents unnecessary processing.


86-96: Thinking budget parsing logic is correct.

The logic properly handles the -thinking-<number> suffix format, validates the numeric value, and applies budget clamping. The error handling for invalid numbers is appropriate (silently ignoring invalid values).


117-128: Correct handling of -nothinking suffix with minimum budget constraints.

The logic properly handles the case where models with minimum thinking budget limits cannot have zero thinking budget, which aligns with the PR objective about Google's API behavior.


130-149: Thoughts summary logic correctly implements the new decoupled behavior.

The implementation properly:

  1. Checks if thoughts summary is enabled globally
  2. Verifies model support
  3. Applies the summary setting except when -nothinking is used with models that allow zero thinking budgets
  4. Handles the case where models with minimum thinking budgets still produce thoughts content

This addresses the main PR objective of decoupling thoughts summary from thinking budget.


172-173: Excellent refactoring that improves code maintainability.

Replacing the complex inline logic with a single function call makes the code much cleaner and easier to maintain. The refactoring successfully centralizes all thinking adaptation logic.


81-150: Verify that all previous inline logic has been correctly migrated.

The new function appears to implement all the necessary logic, but it's important to ensure that no edge cases or behaviors from the previous inline implementation were missed during the refactoring.

Run the following script to verify that no thinking-related logic remains in the old location:

#!/bin/bash
# Description: Check for any remaining thinking-related logic that might have been missed during refactoring

# Search for thinking-related patterns in the relay-gemini.go file
echo "Searching for any remaining thinking-related logic patterns:"
rg -A 5 -B 5 "(thinking|ThinkingConfig|IncludeThoughts)" relay/channel/gemini/relay-gemini.go

echo -e "\nSearching for thinking budget calculations:"
rg -A 3 -B 3 "(ThinkingAdapterBudgetTokensPercentage|ThinkingBudget)" relay/channel/gemini/

echo -e "\nSearching for model suffix handling:"
rg -A 3 -B 3 "(-thinking|-nothinking)" relay/channel/gemini/relay-gemini.go

Comment thread relay/channel/gemini/relay-gemini.go
@Calcium-Ion
Calcium-Ion changed the base branch from main to alpha June 21, 2025 09:03
@9Ninety
9Ninety changed the base branch from alpha to main June 21, 2025 23:14
@9Ninety
9Ninety changed the base branch from main to alpha June 21, 2025 23:16
@9Ninety 9Ninety changed the title feat: add thinking summaries option for gemini [WIP] feat: add thinking summaries option for gemini Jun 21, 2025
@9Ninety 9Ninety changed the title [WIP] feat: add thinking summaries option for gemini feat: add thinking summaries option for gemini Jun 21, 2025
@9Ninety

9Ninety commented Jun 22, 2025

Copy link
Copy Markdown
Contributor Author

@Calcium-Ion I've updated the PR to align with the latest behavior on the alpha branch

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.

1 participant