Skip to content

fix: correct Gemini channel model retrieval logic - #1486

Merged
Calcium-Ion merged 1 commit into
QuantumNous:alphafrom
nekohy:fix-get-google-models
Aug 2, 2025
Merged

fix: correct Gemini channel model retrieval logic#1486
Calcium-Ion merged 1 commit into
QuantumNous:alphafrom
nekohy:fix-get-google-models

Conversation

@nekohy

@nekohy nekohy commented Aug 2, 2025

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Added support for handling a new response format from Gemini channels when fetching upstream models.
  • Bug Fixes

    • Improved compatibility with different channel types by adapting to their specific response formats.

@coderabbitai

coderabbitai Bot commented Aug 2, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The code introduces support for a new "Gemini" channel type in the FetchUpstreamModels function. It adds data structures to handle Gemini's unique model response format, adjusts URL and header logic for Gemini requests, and implements conditional parsing to convert Gemini responses into the existing OpenAI-compatible format.

Changes

Cohort / File(s) Change Summary
Gemini Channel Support & Response Parsing
controller/channel.go
Added structs for Gemini response format, updated URL and header logic for Gemini, and implemented conditional parsing to handle Gemini and OpenAI model responses.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller
    participant Upstream (Gemini/OpenAI/Ali)

    Client->>Controller: FetchUpstreamModels(channelType)
    Controller->>Upstream: HTTP GET (URL & headers based on channelType)
    Upstream-->>Controller: Response (Gemini or OpenAI format)
    alt Gemini response
        Controller->>Controller: Parse as Gemini format
        Controller->>Controller: Convert to OpenAI-compatible format
    else OpenAI response
        Controller->>Controller: Parse as OpenAI format
    end
    Controller-->>Client: Model list (OpenAI-compatible)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

A Gemini breeze through the channels blew,
With structs and logic, something new.
URLs now twist, headers aware,
Parsing with care for models to share.
OpenAI or Gemini, no need to choose—
The code adapts, so none can lose!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • 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
🪧 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 generate unit tests to generate unit tests for 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: 2

🧹 Nitpick comments (2)
controller/channel.go (2)

205-205: Clarify the comment about Gemini's authentication method.

The comment "I don't know why" can be improved to explain that Gemini uses API key as a query parameter instead of an Authorization header.

-		body, err = GetResponseBody("GET", url, channel, nil) // I don't know why, but Gemini requires no AuthHeader
+		body, err = GetResponseBody("GET", url, channel, nil) // Gemini uses API key in URL query parameter instead of Authorization header

239-239: Use English for error messages for consistency.

Error messages should be in English to maintain consistency and improve international compatibility.

-				"message": fmt.Sprintf("解析响应失败: %s", err.Error()),
+				"message": fmt.Sprintf("Failed to parse response: %s", err.Error()),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 74ec34d and 71e9290.

📒 Files selected for processing (1)
  • controller/channel.go (2 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: 9Ninety
PR: QuantumNous/new-api#1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
📚 Learning: in relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the maxout...
Learnt from: 9Ninety
PR: QuantumNous/new-api#1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.

Applied to files:

  • controller/channel.go

Comment thread controller/channel.go
Comment on lines +39 to +51
type GoogleOpenAICompatibleModels []struct {
Name string `json:"name"`
Version string `json:"version"`
DisplayName string `json:"displayName"`
Description string `json:"description,omitempty"`
InputTokenLimit int `json:"inputTokenLimit"`
OutputTokenLimit int `json:"outputTokenLimit"`
SupportedGenerationMethods []string `json:"supportedGenerationMethods"`
Temperature float64 `json:"temperature,omitempty"`
TopP float64 `json:"topP,omitempty"`
TopK int `json:"topK,omitempty"`
MaxTemperature int `json:"maxTemperature,omitempty"`
}

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

Fix incorrect type definition causing unnecessary nesting.

The type GoogleOpenAICompatibleModels is already defined as a slice, but in GoogleOpenAICompatibleResponse, it's used as []GoogleOpenAICompatibleModels, creating a slice of slices. This appears to be a mistake based on the usage pattern.

Apply this diff to fix the type definitions:

-type GoogleOpenAICompatibleModels []struct {
+type GoogleOpenAICompatibleModel struct {
 	Name                       string   `json:"name"`
 	Version                    string   `json:"version"`
 	DisplayName                string   `json:"displayName"`
 	Description                string   `json:"description,omitempty"`
 	InputTokenLimit            int      `json:"inputTokenLimit"`
 	OutputTokenLimit           int      `json:"outputTokenLimit"`
 	SupportedGenerationMethods []string `json:"supportedGenerationMethods"`
 	Temperature                float64  `json:"temperature,omitempty"`
 	TopP                       float64  `json:"topP,omitempty"`
 	TopK                       int      `json:"topK,omitempty"`
 	MaxTemperature             int      `json:"maxTemperature,omitempty"`
 }

 type GoogleOpenAICompatibleResponse struct {
-	Models        []GoogleOpenAICompatibleModels `json:"models"`
+	Models        []GoogleOpenAICompatibleModel `json:"models"`
 	NextPageToken string                         `json:"nextPageToken"`
 }

Also applies to: 58-61

🤖 Prompt for AI Agents
In controller/channel.go around lines 39 to 51 and 58 to 61, the type
GoogleOpenAICompatibleModels is defined as a slice of structs, but it is used as
a slice of GoogleOpenAICompatibleModels elsewhere, causing an unintended slice
of slices. To fix this, redefine GoogleOpenAICompatibleModels as a single struct
instead of a slice, and update all references to use a slice of this struct
type, eliminating the extra nesting.

Comment thread controller/channel.go
Comment on lines +223 to +229
for _, model := range googleResult.Models {
for _, gModel := range model {
result.Data = append(result.Data, OpenAIModel{
ID: gModel.Name,
})
}
}

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

Simplify the nested loop after fixing the type definition.

Once the type definition is fixed as suggested above, this double nested loop should be simplified.

After applying the struct fix, update this code:

-			for _, model := range googleResult.Models {
-				for _, gModel := range model {
-					result.Data = append(result.Data, OpenAIModel{
-						ID: gModel.Name,
-					})
-				}
-			}
+			for _, model := range googleResult.Models {
+				result.Data = append(result.Data, OpenAIModel{
+					ID: model.Name,
+				})
+			}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for _, model := range googleResult.Models {
for _, gModel := range model {
result.Data = append(result.Data, OpenAIModel{
ID: gModel.Name,
})
}
}
for _, model := range googleResult.Models {
result.Data = append(result.Data, OpenAIModel{
ID: model.Name,
})
}
🤖 Prompt for AI Agents
In controller/channel.go around lines 223 to 229, after correcting the type
definition of googleResult.Models as suggested, simplify the nested loops by
iterating directly over the corrected slice or map structure without the
unnecessary inner loop. Adjust the loop to a single level that appends
OpenAIModel instances to result.Data using the corrected type elements.

@Calcium-Ion
Calcium-Ion merged commit e6c8790 into QuantumNous:alpha Aug 2, 2025
3 checks passed
@nekohy
nekohy deleted the fix-get-google-models branch August 2, 2025 13:57
This was referenced Aug 2, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Apr 22, 2026
11 tasks
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
fix: correct Gemini channel model retrieval logic
@coderabbitai coderabbitai Bot mentioned this pull request May 1, 2026
8 tasks
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