Skip to content

Refactor: Extract model variant expansion and optimize tool handling in adapter-gemini#744

Merged
dingyi222666 merged 4 commits into
v1-devfrom
feat/adapter-gemini
Feb 26, 2026
Merged

Refactor: Extract model variant expansion and optimize tool handling in adapter-gemini#744
dingyi222666 merged 4 commits into
v1-devfrom
feat/adapter-gemini

Conversation

@dingyi222666
Copy link
Copy Markdown
Member

Summary

This PR refactors the Gemini adapter to improve code organization and maintainability by extracting model variant expansion logic and optimizing tool handling mechanisms.

New Features

  • Extracted model variant expansion into separate utility functions for better code reusability
  • Improved tool handling logic in the Gemini adapter client

Bug fixes

None

Other Changes

  • Version bump to 1.3.26
  • Refactored packages/adapter-gemini/src/client.ts with improved structure
  • Expanded packages/adapter-gemini/src/utils.ts with new helper utilities
  • Updated schema localization files (en-US and zh-CN)

…e tool handling

- Extract model variant expansion logic into reusable utility functions (expandModelVariants, pushImageVariants, etc.) for better code organization and maintainability
- Add support for image generation models with resolution and search suffix variants (-2k, -4k, -0.5k, -search)
- Implement imageModelSearch config option to enable search functionality for image generation models, generating -search variant suffixes
- Extract tool configuration logic from formatToolsToGeminiAITools into appendBuiltinTools helper function for cleaner separation of concerns
- Add model support lists (CUSTOM_TOOLS_UNSUPPORTED_MODELS, IMAGE_GENERATION_MODELS, IMAGE_SEARCH_SUPPORTED_MODELS) as module-level constants for better maintainability
- Enhance model config parsing to handle -search suffix for forcing Google search on image generation models
- Fix regex pattern for thinking level detection to support gemini-3.1-pro family models
- Fix image size extraction regex to support additional resolution formats (0.5k) with case-insensitive matching
- Add forceGoogleSearch flag to model config to enable search on image models when -search suffix is present
- Update safety settings to use modelConfig.model instead of params.model for consistency
- Add comprehensive JSDoc comments documenting model variant expansion rules
- Add code regions (#region / #endregion) for better code navigation in GeminiClient
- Update English and Chinese locales with imageModelSearch configuration description
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Feb 26, 2026

Warning

Rate limit exceeded

@dingyi222666 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 5 minutes and 33 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 9ce4308 and 63c5296.

⛔ Files ignored due to path filters (1)
  • packages/adapter-gemini/package.json is excluded by !**/*.json
📒 Files selected for processing (2)
  • packages/adapter-gemini/src/client.ts
  • packages/adapter-gemini/src/utils.ts

Walkthrough

此PR为Gemini适配器引入了集中化的模型变体扩展机制,通过新增expandModelVariants函数替代之前分散在客户端的变体处理逻辑,并添加imageModelSearch配置选项及全面的模型分类和工具管理功能。

Changes

Cohort / File(s) Summary
模型变体扩展中枢
packages/adapter-gemini/src/utils.ts
引入全面的模型变体机制:包括IMAGE_VARIANT_MODELS配置、expandModelVariants函数、图像分辨率和思考模式变体检测、isThinkingModel/isThinkingLevelModel分类函数,以及内置工具管理逻辑(appendBuiltinTools、forceGoogleSearch机制)。prepareModelConfig扩展返回forceGoogleSearch字段。
客户端重构
packages/adapter-gemini/src/client.ts
重构refreshModels流程,将模型变体扩展逻辑委托给新的expandModelVariants函数,移除之前的内联变体处理(图像分辨率、thinking变体、级别相关逻辑)和辅助函数(pushExpanded、includesAny)。
配置扩展
packages/adapter-gemini/src/index.ts
在Config接口及schema中添加新的imageModelSearch布尔配置选项,默认值为false。

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 模型生花,变体绽放,
统一扩展,逻辑绽香,
search与thinking织梦幻,
图像分辨,精妙非常~

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ 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%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed PR标题'Refactor: Extract model variant expansion and optimize tool handling in adapter-gemini'准确概括了主要变更——重构代码组织以提取模型变体扩展和优化工具处理逻辑。
Description check ✅ Passed PR描述与变更集密切相关,涵盖提取模型变体扩展、优化工具处理逻辑、版本更新等内容,与实际代码变更相符。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/adapter-gemini

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.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @dingyi222666, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the Gemini adapter by improving its internal architecture and expanding its capabilities. The primary goal was to centralize and streamline the complex logic involved in generating various model configurations and managing tool integrations. This refactoring leads to a more modular, maintainable, and extensible codebase, particularly for handling diverse Gemini model variants and their associated features like image search.

Highlights

  • Model Variant Expansion Refactoring: The logic for expanding Gemini model variants (e.g., thinking levels, image resolutions, search suffixes) has been extracted into dedicated utility functions in utils.ts, significantly simplifying the GeminiClient's refreshModels method.
  • Optimized Tool Handling: The formatToolsToGeminiAITools function has been refactored with new helper functions to better manage built-in tools (Google Search, Code Execution, URL Context), including specific handling for models that do not support certain tools and new image search capabilities.
  • New Image Model Search Option: A new configuration option imageModelSearch has been introduced, allowing supported image generation models to generate additional variants with a -search suffix, enabling combined image and web search.
  • Version Update: The package version for adapter-gemini has been incremented to 1.3.26.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • packages/adapter-gemini/package.json
    • Updated package version from 1.3.25 to 1.3.26.
  • packages/adapter-gemini/src/client.ts
    • Imported expandModelVariants from utils.ts.
    • Added region comments to improve code organization.
    • Refactored the refreshModels method to delegate model variant expansion to the new expandModelVariants utility function, removing complex inline logic.
  • packages/adapter-gemini/src/index.ts
    • Added imageModelSearch boolean property to the Config interface.
    • Included imageModelSearch with a default value of false in the configuration schema.
  • packages/adapter-gemini/src/locales/en-US.schema.yml
    • Added a description for the new imageModelSearch configuration option.
  • packages/adapter-gemini/src/locales/zh-CN.schema.yml
    • 为新的 imageModelSearch 配置项添加了描述。
  • packages/adapter-gemini/src/utils.ts
    • Imported ModelInfo type.
    • Defined constants CUSTOM_TOOLS_UNSUPPORTED_MODELS, IMAGE_GENERATION_MODELS, and IMAGE_SEARCH_SUPPORTED_MODELS for better tool handling logic.
    • Added helper functions isCustomToolsUnsupported, isImageSearchSupported, and appendBuiltinTools to encapsulate tool-related checks and appending logic.
    • Refactored formatToolsToGeminiAITools to utilize the new tool handling helper functions, including support for imageModelSearch.
    • Modified prepareModelConfig to extract a forceGoogleSearch flag from model names ending with -search and updated the regex for image size extraction to support 0.5k and case-insensitive matching.
    • Introduced a suite of helper functions (THINKING_MODELS, THINKING_LEVEL_MODELS, IMAGE_VARIANT_MODELS, includesAny, pushExpanded, getImageVariantConfig, pushImageVariants, isGemini3ProFamily, isThinkingModel, isThinkingLevelModel, expandModelVariants) to centralize and manage the logic for expanding model variants.
Activity
  • The pull request introduces significant refactoring and new features, as detailed in the highlights and changelog.
  • No specific human review comments or progress updates are available in the provided context.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9ce4308da5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/adapter-gemini/src/utils.ts
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a significant refactoring of the Gemini adapter, primarily by extracting the logic for model variant expansion and tool handling into utility functions. This greatly improves code organization, readability, and maintainability. The changes also include enhancements like support for new model variants (e.g., gemini-3.1-pro, gemini-3.1-flash-image) and a new -search suffix to force Google Search. The overall changes are well-executed and represent a solid improvement to the codebase. I have a couple of suggestions for minor improvements to further enhance code clarity and reduce duplication.

Comment thread packages/adapter-gemini/src/utils.ts Outdated
Comment thread packages/adapter-gemini/src/utils.ts
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
packages/adapter-gemini/src/utils.ts (1)

394-399: 禁用分支日志与实际行为不一致

该分支同时关闭了 googleSearchcodeExecutionurlContext,但日志只提示了 google search,建议同步文案,避免误导排障。

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/adapter-gemini/src/utils.ts` around lines 394 - 399, The warning
message in logger.warn is misleading because the branch disables googleSearch,
codeExecution, and urlContext but only mentions google search; update the
logger.warn call (referencing logger.warn and the model variable) to clearly
list all disabled features (googleSearch, codeExecution, urlContext) or
alternatively change the assignments to only disable googleSearch if that was
intended; ensure the log text and the boolean assignments (googleSearch,
codeExecution, urlContext) remain consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/adapter-gemini/src/client.ts`:
- Around line 100-103: refreshModels calls expandModelVariants(models, baseInfo)
but doesn't pass the imageModelSearch flag, so "-search" variants are always
generated; update the call in refreshModels to pass the config (e.g.,
expandModelVariants(models, baseInfo, imageModelSearch)) and adjust
expandModelVariants' signature/implementation to accept and honor that third
boolean parameter (imageModelSearch) so variant generation respects the flag;
ensure all other call sites of expandModelVariants are updated accordingly or
given a default to preserve backward compatibility.

In `@packages/adapter-gemini/src/utils.ts`:
- Around line 369-371: The early return checks only "tools.length < 1 &&
!config.googleSearch" which wrongly skips built-in tools when other flags like
codeExecution or urlContext are enabled; update the condition around the "return
undefined" to only return when tools is empty AND none of the built-in feature
flags are enabled (e.g. config.googleSearch, config.codeExecution,
config.urlContext — include any other built-in flags present), so that if any
built-in (codeExecution, urlContext, googleSearch, etc.) is enabled the code
continues to register and emit built-in tools.

---

Nitpick comments:
In `@packages/adapter-gemini/src/utils.ts`:
- Around line 394-399: The warning message in logger.warn is misleading because
the branch disables googleSearch, codeExecution, and urlContext but only
mentions google search; update the logger.warn call (referencing logger.warn and
the model variable) to clearly list all disabled features (googleSearch,
codeExecution, urlContext) or alternatively change the assignments to only
disable googleSearch if that was intended; ensure the log text and the boolean
assignments (googleSearch, codeExecution, urlContext) remain consistent.

ℹ️ Review info

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 71804dc and 9ce4308.

⛔ Files ignored due to path filters (3)
  • packages/adapter-gemini/package.json is excluded by !**/*.json
  • packages/adapter-gemini/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/adapter-gemini/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
📒 Files selected for processing (3)
  • packages/adapter-gemini/src/client.ts
  • packages/adapter-gemini/src/index.ts
  • packages/adapter-gemini/src/utils.ts

Comment thread packages/adapter-gemini/src/client.ts
Comment thread packages/adapter-gemini/src/utils.ts
dingyi222666 and others added 2 commits February 27, 2026 01:45
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
…nt expansion

- Pass imageModelSearch config to expandModelVariants for image model handling
- Update pushImageVariants to conditionally generate -search suffixes based on imageModelSearch flag
- Enhance formatToolsToGeminiAITools validation to check codeExecution and urlContext configs
- Improve documentation comments for image variant generation and model expansion logic
@dingyi222666 dingyi222666 merged commit dfbf575 into v1-dev Feb 26, 2026
5 checks passed
@dingyi222666 dingyi222666 deleted the feat/adapter-gemini branch February 27, 2026 17:38
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