Skip to content

feat: improve gemini thinking budget adaption - #1247

Merged
Calcium-Ion merged 1 commit into
QuantumNous:alphafrom
RedwindA:feat/25lite-thinking
Jun 17, 2025
Merged

feat: improve gemini thinking budget adaption#1247
Calcium-Ion merged 1 commit into
QuantumNous:alphafrom
RedwindA:feat/25lite-thinking

Conversation

@RedwindA

@RedwindA RedwindA commented Jun 17, 2025

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Refactor

    • Improved consistency in how thinking budget limits are enforced across different models.
    • Updated handling for model-specific options related to thinking budget, with clearer restrictions for certain model types.
  • Bug Fixes

    • Resolved inconsistencies in thinking budget validation for various models.

@coderabbitai

coderabbitai Bot commented Jun 17, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change introduces a helper function to centralize and standardize the logic for clamping the "thinking budget" parameter for different Gemini model variants. The refactoring updates how model name suffixes related to thinking budgets are parsed and validated, ensuring consistent handling across model types.

Changes

File(s) Change Summary
relay/channel/gemini/relay-gemini.go Added clampThinkingBudget function; refactored thinking budget parsing and validation logic; updated suffix handling for model-specific constraints.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant CovertGemini2OpenAI
    participant clampThinkingBudget

    Client->>CovertGemini2OpenAI: Request with model name (may include -thinking- or -nothinking)
    CovertGemini2OpenAI->>clampThinkingBudget: Validate and clamp thinking budget for model
    clampThinkingBudget-->>CovertGemini2OpenAI: Return clamped budget
    CovertGemini2OpenAI-->>Client: Proceed with validated budget
Loading

Possibly related PRs

Poem

A rabbit hopped through Gemini's code,
Tidying budgets wherever they showed.
No more scattered clamps or checks,
Just one neat function—what the heck!
Now thinking's clear, concise, and bright,
The models ponder just right!
🐇✨

✨ 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 (3)
relay/channel/gemini/relay-gemini.go (3)

42-46: Prefer clearer, model-scoped constant names

pro25MinBudget, flash25MaxBudget, etc. are easy to confuse across branches. Prefixing with the model family (e.g. gemini25ProMinBudget) reduces the mental mapping cost and prevents accidental cross-use later.

-const (
-	pro25MinBudget       = 128
+const (
+	gemini25ProMinBudget = 128
   …
 )

101-108: Model-variant detection duplicated

isNew25Pro / is25FlashLite are recalculated here although identical logic exists inside clampThinkingBudget. Consider re-using a shared helper to avoid subtle divergence when the list of preview models changes.


119-144: Round percentage-derived budgets instead of truncating

Casting the float → int with int(budgetTokens) always floors the value. For small budgets that can drop the limit by almost one token batch. Use math.Round (or math.Ceil) for clearer intent:

-import "strconv"
+import (
+	"strconv"
+	"math"
+)

// …
- budgetTokens := model_setting.GetGeminiSettings().ThinkingAdapterBudgetTokensPercentage *
-     float64(geminiRequest.GenerationConfig.MaxOutputTokens)
- clampedBudget := clampThinkingBudget(modelName, int(budgetTokens))
+ raw := model_setting.GetGeminiSettings().ThinkingAdapterBudgetTokensPercentage *
+     float64(geminiRequest.GenerationConfig.MaxOutputTokens)
+ clampedBudget := clampThinkingBudget(modelName, int(math.Round(raw)))
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3a7ba57 and 21f43b0.

📒 Files selected for processing (1)
  • relay/channel/gemini/relay-gemini.go (3 hunks)
🔇 Additional comments (2)
relay/channel/gemini/relay-gemini.go (2)

108-118: Validate parsed budget before clamping

If the suffix contains a non-positive number (e.g. -thinking--5 or -thinking-0), we silently coerce it to the model’s minimum. Returning a user-visible error would surface mis-configuration earlier and keeps API behaviour explicit.


144-150: Blocking -nothinking for flash-lite looks correct

Extending the restriction beyond 2.5-pro to include 2.5-flash-lite aligns with the published limits. No issues spotted.

Comment on lines +49 to +79
// clampThinkingBudget 根据模型名称将预算限制在允许的范围内
func clampThinkingBudget(modelName string, budget int) int {
isNew25Pro := strings.HasPrefix(modelName, "gemini-2.5-pro") &&
!strings.HasPrefix(modelName, "gemini-2.5-pro-preview-05-06") &&
!strings.HasPrefix(modelName, "gemini-2.5-pro-preview-03-25")
is25FlashLite := strings.HasPrefix(modelName, "gemini-2.5-flash-lite")

if is25FlashLite {
if budget < flash25LiteMinBudget {
return flash25LiteMinBudget
}
if budget > flash25LiteMaxBudget {
return flash25LiteMaxBudget
}
} else if isNew25Pro {
if budget < pro25MinBudget {
return pro25MinBudget
}
if budget > pro25MaxBudget {
return pro25MaxBudget
}
} else { // 其他模型
if budget < 0 {
return 0
}
if budget > flash25MaxBudget {
return flash25MaxBudget
}
}
return budget
}

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.

🛠️ Refactor suggestion

clampThinkingBudget mixes concerns & repeats model-detection logic

  1. The isNew25Pro / is25FlashLite checks will soon live in at least three places (here, in CovertGemini2OpenAI, and very likely in request validation). A single helper such as detectGeminiVariant(modelName) (variant enum) would avoid drift.

  2. For negative budgets the function silently upgrades to the model’s minimum (128 / 512). That might be desirable, but it is implicit. At minimum add a short doc-comment or, better, reject negatives and let the caller decide:

-	if budget < pro25MinBudget {
-		return pro25MinBudget
+	if budget <= 0 {
+		return pro25MinBudget // or: return 0, signalling “invalid”
  1. The max for “other models” is flash25MaxBudget; consider renaming that constant or adding a comment so the cap doesn’t look arbitrary.

Refactoring sketch (compressed):

type geminiVariant int
const (
	varUnknown geminiVariant = iota
	var25Pro
	var25FlashLite
	varOther
)

func detectVariant(m string) geminiVariant { … }

func clampBudget(v geminiVariant, b int) int { … }

This removes string-prefix checks from every caller.

🤖 Prompt for AI Agents
In relay/channel/gemini/relay-gemini.go around lines 49 to 79, the
clampThinkingBudget function mixes model detection logic with budget clamping,
causing repeated string-prefix checks and implicit handling of negative budgets.
Refactor by extracting model detection into a separate helper function
detectGeminiVariant(modelName) returning a variant enum, then rewrite
clampThinkingBudget to accept this variant and budget, explicitly rejecting
negative budgets or documenting behavior clearly. Also, rename or comment the
flash25MaxBudget constant used as max for other models to clarify its purpose
and avoid confusion.

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