Repository navigation
Go: add new provider: google - #14395
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughAdds Google GenAI provider support (Gemini) with configuration and a new Go driver implementing chat, streaming, and model listing; updates dependencies; wires the provider into the factory; moves “thinking” config to per-model fields; and adjusts streaming error/flow handling across service and handler layers. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Provider as GoogleModel
participant GenAI as Google GenAI API
rect rgba(100, 150, 200, 0.5)
Note over Client,GenAI: Synchronous Chat
Client->>Provider: Chat(modelName, message, apiConfig, chatModelConfig)
Provider->>Provider: Create GenAI client with API key & region
Provider->>GenAI: Models.GenerateContent(request)
GenAI-->>Provider: Response (text, optional thinking)
Provider-->>Client: ChatResponse (Answer, ReasonContent?)
end
rect rgba(150, 150, 100, 0.5)
Note over Client,GenAI: Streaming Chat
Client->>Provider: ChatStreamlyWithSender(..., sender)
Provider->>Provider: Create GenAI streaming client
Provider->>GenAI: Models.GenerateContentStream(request)
GenAI-->>Provider: Stream chunks (thinking/content)
Provider->>Client: sender(reasoningChunk, nil) / sender(nil, contentChunk) [multiple]
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (2)
internal/entity/models/google.go (2)
60-66: SimplifyThinkingConfigsetup.The
elsebranch is redundant —IncludeThoughtsdefaults to the zero value (false). You can collapse this to a single assignment.- generateContentConfig := &genai.GenerateContentConfig{} - generateContentConfig.ThinkingConfig = &genai.ThinkingConfig{} - if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { - generateContentConfig.ThinkingConfig.IncludeThoughts = true - } else { - generateContentConfig.ThinkingConfig.IncludeThoughts = false - } + generateContentConfig := &genai.GenerateContentConfig{ + ThinkingConfig: &genai.ThinkingConfig{ + IncludeThoughts: chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking, + }, + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/google.go` around lines 60 - 66, The code in generateContentConfig.ThinkingConfig setup is verbose: remove the redundant else and directly set generateContentConfig.ThinkingConfig.IncludeThoughts = chatModelConfig.Thinking != nil && *chatModelConfig.Thinking; update the block around generateContentConfig and generateContentConfig.ThinkingConfig to initialize ThinkingConfig and assign IncludeThoughts in a single statement using the chatModelConfig.Thinking check (refer to variables generateContentConfig, generateContentConfig.ThinkingConfig, and chatModelConfig.Thinking).
144-165: Handle pagination and filter by model capability.
client.Models.Listreturns paginated results viaPage[Model]. The current code only processes the first page (models.Items), missing remaining results when aNextPageTokenexists. Additionally, the Gemini API returns all models including embeddings and legacy variants, but the use case is chat-only. UsemodelsPage.all(ctx)to iterate all pages, and filter by checking each model'sSupportedActionsfield for"generateContent":Example approach
modelsPage, err := client.Models.List(ctx, &genai.ListModelsConfig{}) if err != nil { return nil, err } var modelNames []string allModels := modelsPage.all(ctx) for model := range allModels { for _, action := range model.SupportedActions { if action == "generateContent" { modelNames = append(modelNames, model.Name) break } } } return modelNames, nil🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/models/google.go` around lines 144 - 165, The ListModels method currently only processes the first page returned by client.Models.List and returns all model types; update GoogleModel.ListModels to iterate all pages using the modelsPage.all(ctx) iterator returned from client.Models.List and filter each model by checking model.SupportedActions for the "generateContent" action so only chat-capable models are included; keep building the modelNames slice and return it as before.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@conf/models/google.json`:
- Around line 26-31: The ReasoningEffort JSON blocks are misaligned with the
internal ReasoningEffort struct (type, enabled, default, options): replace
"default_value" with "default", rename "supported_modes" to "options", and add
the missing "type" and "enabled" keys with appropriate values in the
reasoning_effort objects; update both google.json and deepseek.json so their
reasoning_effort entries match the ReasoningEffort struct field names and
expected types (ensure "options" is an array and "default" matches one of its
entries).
In `@internal/entity/models/google.go`:
- Line 27: The doc comment above GoogleModel is stale (mentions "Dummy AI");
update the comment to accurately describe GoogleModel and its role implementing
ModelDriver (e.g., "GoogleModel implements ModelDriver for Google AI/Google
model provider"), ensuring the exported type name GoogleModel has a matching,
precise doc comment and remove any leftover references to DummyModel.
- Line 24: The import "google.golang.org/genai" is missing from go.mod causing
build failures; update the module dependencies by adding the genai module (e.g.
run `go get google.golang.org/genai@latest` or add the appropriate version to
go.mod) and run `go mod tidy` to ensure the dependency is recorded and other
unused entries cleaned up so the import in internal/entity/models/google.go
resolves.
- Around line 92-137: ChatStreamlyWithSender has multiple bugs: create and pass
a non-nil GenerateContentConfig (same as Chat) enabling
ThinkingConfig.IncludeThoughts when chatModelConfig.Thinking is set; inside the
stream loop, don't assume Candidates/Content.Parts exist—check lengths and
filter Parts by IsThought (use
response.Candidates[i].Content.Parts[j].IsThought) so thought parts go to the
thinking path and answer parts to the content path; fix the logging call to
print the actual answer variable (use content for "Answer") and lower sensitive
logs to debug; capture the loop-scoped err from the GenerateContentStream
iterator into a local variable and return that (or return nil explicitly if you
decide not to propagate iterator errors); locate fixes around
ChatStreamlyWithSender, GenerateContentConfig/ThinkingConfig,
response.Candidates/Content.Parts, response.Text, and sender.
- Around line 1-173: The model factory's switch that instantiates model drivers
is missing a branch for Google so configs with provider "google" fall through to
the default Dummy model; add a case "google" branch in the factory's switch to
return NewGoogleModel(baseURL, urlSuffix), nil (ensure the factory function that
builds models references NewGoogleModel and its types exactly as declared in
GoogleModel).
- Around line 167-173: The CheckConnection method on GoogleModel currently
returns fmt.Errorf("no such method"), which breaks health/startup checks; update
GoogleModel.CheckConnection to return nil for a supported provider (or
preferably perform a lightweight validation by constructing a Google client and
making a minimal call such as client.Models.List or another cheap API call to
verify the API key and return any error), while leaving Balance as-is; ensure
the method uses the APIConfig input to build the client and returns nil on
success or the underlying error on failure.
- Around line 46-84: Guard against nil API config and nil ApiKey in
GoogleModel.Chat (check apiConfig != nil && apiConfig.ApiKey != nil and return a
clear error) and avoid dereferencing *apiConfig.ApiKey without checks; add
similar guards where ApiKey is used later. Add defensive checks on response
before indexing: verify len(response.Candidates) > 0,
response.Candidates[0].Content != nil and iterate over
response.Candidates[0].Content.Parts (checking len and p.Thought) to build
ReasonContent instead of assuming Parts[0] contains a thought. Also stop
creating a genai client on every call: initialize and cache the genai.Client on
the GoogleModel receiver (lazily create it in GoogleModel.Chat using
genai.NewClient only if the cached client is nil) to reuse the client and avoid
per-request construction.
---
Nitpick comments:
In `@internal/entity/models/google.go`:
- Around line 60-66: The code in generateContentConfig.ThinkingConfig setup is
verbose: remove the redundant else and directly set
generateContentConfig.ThinkingConfig.IncludeThoughts = chatModelConfig.Thinking
!= nil && *chatModelConfig.Thinking; update the block around
generateContentConfig and generateContentConfig.ThinkingConfig to initialize
ThinkingConfig and assign IncludeThoughts in a single statement using the
chatModelConfig.Thinking check (refer to variables generateContentConfig,
generateContentConfig.ThinkingConfig, and chatModelConfig.Thinking).
- Around line 144-165: The ListModels method currently only processes the first
page returned by client.Models.List and returns all model types; update
GoogleModel.ListModels to iterate all pages using the modelsPage.all(ctx)
iterator returned from client.Models.List and filter each model by checking
model.SupportedActions for the "generateContent" action so only chat-capable
models are included; keep building the modelNames slice and return it as before.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 64da8d6f-f02e-42e3-ac64-bb686bc2f77d
📒 Files selected for processing (2)
conf/models/google.jsoninternal/entity/models/google.go
| "reasoning_effort": { | ||
| "default_value": "high", | ||
| "supported_modes": [ | ||
| "gemini-2.5-flash" | ||
| ] | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify the JSON schema for the reasoning_effort feature in the Features struct,
# and check how other provider configs spell this key.
rg -nP --type=go -C3 '\bReasoningEffort\b|reasoning_effort'
echo '---'
rg -nP -C2 '"reasoning_effort"' conf/models/
echo '---'
rg -nP -C2 '"supported_mode' conf/models/Repository: infiniflow/ragflow
Length of output: 7054
🏁 Script executed:
# Get the full ReasoningEffort struct definition
rg -nP -A10 'type ReasoningEffort struct' internal/entity/model.go
echo '---'
# Check for unmarshaling logic or handling of supported_modes/models for reasoning_effort
rg -nP -B3 -A3 'SupportedMode' internal/entity/model.goRepository: infiniflow/ragflow
Length of output: 1481
🏁 Script executed:
# Check how reasoning_effort JSON is actually expected to be structured
rg -nP -B5 -A10 'reasoning_effort' internal/entity/model.go | head -50
echo '---'
# Look for any custom unmarshaling for reasoning_effort
rg -nP -A15 'type ReasoningEffort' internal/entity/model.go
echo '---'
# Compare with how thinking/clear_thinking handle their JSON structure
rg -nP 'DefaultValue|SupportedModels' internal/entity/model.go | head -20Repository: infiniflow/ragflow
Length of output: 1782
🏁 Script executed:
# Check custom unmarshaling for Reasoning/ReasoningEffort
rg -nP -A30 'func.*Reasoning.*UnmarshalJSON|case "effort"' internal/entity/model.go
echo '---'
# Verify what the actual expected JSON structure should be
rg -nP -B2 -A8 '"reasoning"' conf/models/ | head -60Repository: infiniflow/ragflow
Length of output: 3647
Incorrect diagnosis: multiple field misalignments, not just supported_modes → supported_models.
The ReasoningEffort struct expects fields type, enabled, default, and options (lines 47–52 in internal/entity/model.go). The reasoning_effort block in google.json uses:
"default_value"(should be"default")"supported_modes"(should be"options")- Missing
"type"and"enabled"fields entirely
The original comment conflates this with the Thinking struct, which uses SupportedModels; however, ReasoningEffort has no such field. The correct fixes are:
"reasoning_effort": {
- "default_value": "high",
+ "type": "effort",
+ "enabled": true,
+ "default": "high",
- "supported_modes": [
+ "options": [
"gemini-2.5-flash"
]
}Same issues exist in deepseek.json (lines 35–39).
📝 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.
| "reasoning_effort": { | |
| "default_value": "high", | |
| "supported_modes": [ | |
| "gemini-2.5-flash" | |
| ] | |
| } | |
| "reasoning_effort": { | |
| "type": "effort", | |
| "enabled": true, | |
| "default": "high", | |
| "options": [ | |
| "gemini-2.5-flash" | |
| ] | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@conf/models/google.json` around lines 26 - 31, The ReasoningEffort JSON
blocks are misaligned with the internal ReasoningEffort struct (type, enabled,
default, options): replace "default_value" with "default", rename
"supported_modes" to "options", and add the missing "type" and "enabled" keys
with appropriate values in the reasoning_effort objects; update both google.json
and deepseek.json so their reasoning_effort entries match the ReasoningEffort
struct field names and expected types (ensure "options" is an array and
"default" matches one of its entries).
| "google.golang.org/genai" | ||
| ) | ||
|
|
||
| // GoogleModel implements ModelDriver for Dummy AI |
There was a problem hiding this comment.
Stale doc comment.
Says "Dummy AI" — copy/paste from DummyModel.
-// GoogleModel implements ModelDriver for Dummy AI
+// GoogleModel implements ModelDriver for Google GenAI (Gemini)📝 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.
| // GoogleModel implements ModelDriver for Dummy AI | |
| // GoogleModel implements ModelDriver for Google GenAI (Gemini) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/google.go` at line 27, The doc comment above
GoogleModel is stale (mentions "Dummy AI"); update the comment to accurately
describe GoogleModel and its role implementing ModelDriver (e.g., "GoogleModel
implements ModelDriver for Google AI/Google model provider"), ensuring the
exported type name GoogleModel has a matching, precise doc comment and remove
any leftover references to DummyModel.
| func (z *GoogleModel) Chat(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) { | ||
| ctx := context.Background() | ||
| client, err := genai.NewClient(ctx, &genai.ClientConfig{ | ||
| APIKey: *apiConfig.ApiKey, | ||
| Backend: genai.BackendGeminiAPI, | ||
| }) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| contents := []*genai.Content{ | ||
| genai.NewContentFromText(*message, genai.RoleUser), | ||
| } | ||
|
|
||
| generateContentConfig := &genai.GenerateContentConfig{} | ||
| generateContentConfig.ThinkingConfig = &genai.ThinkingConfig{} | ||
| if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | ||
| generateContentConfig.ThinkingConfig.IncludeThoughts = true | ||
| } else { | ||
| generateContentConfig.ThinkingConfig.IncludeThoughts = false | ||
| } | ||
|
|
||
| response, err := client.Models.GenerateContent(ctx, *modelName, contents, generateContentConfig) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| content := response.Text() | ||
|
|
||
| var responseContent string | ||
| if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | ||
| responseContent = response.Candidates[0].Content.Parts[0].Text | ||
| } | ||
|
|
||
| chatResponse := &ChatResponse{ | ||
| Answer: &content, | ||
| ReasonContent: &responseContent, | ||
| } | ||
| return chatResponse, nil | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
In the google.golang.org/genai Go SDK, when ThinkingConfig.IncludeThoughts is true, how is a thought part identified on genai.Part, and does response.Text() include thought text?
💡 Result:
In the google.golang.org/genai Go SDK, when ThinkingConfig.IncludeThoughts is true, a thought part is identified on genai.Part by checking if the Thought field is true (part.Thought == true). The response.Text method concatenates only the text from non-thought parts and excludes thought text.
Citations:
- 1: https://github.com/googleapis/go-genai/blob/main/types.go
- 2: https://github.com/googleapis/go-genai/blob/main/types_test.go
- 3: https://ai.google.dev/gemini-api/docs/thinking
- 4: googleai: Add support for Gemini 3 thought_signature parameter tmc/langchaingo#1464
- 5: https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thinking
Multiple correctness issues in Chat.
-
Nil-pointer deref on
*apiConfig.ApiKey(line 49). No guard forapiConfig == nilorapiConfig.ApiKey == nil; an empty/missing key will panic instead of returning a clean error. Same issue at lines 95 and 147. -
response.Candidates[0].Content.Parts[0].Text(line 76) is unsafe. No length checks onCandidatesorParts— the API may return an empty list (e.g., blocked/filtered response), causing a panic. -
Unsafe thought extraction (line 76). When thinking is enabled, the code assumes
Parts[0]is a thought part, but doesn't verify this. Sinceresponse.Text()returns only non-thought parts, the thought text must be extracted by iteratingPartsand checking eachpart.Thought == true. As written,ReasonContentmay contain answer text or nothing if the first part is not a thought. -
Client is constructed on every call.
genai.NewClientshould be created once (e.g., lazily cached on the receiver) rather than per-request to avoid TLS/HTTP overhead.
🛡️ Sketch of a safer split
if apiConfig == nil || apiConfig.ApiKey == nil {
return nil, fmt.Errorf("missing API key")
}
// ...
if len(response.Candidates) == 0 || response.Candidates[0].Content == nil {
return nil, fmt.Errorf("empty response from Gemini")
}
var reason string
if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
for _, p := range response.Candidates[0].Content.Parts {
if p.Thought {
reason += p.Text
}
}
}
return &ChatResponse{Answer: response.Text(), ReasonContent: &reason}, nil🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/google.go` around lines 46 - 84, Guard against nil API
config and nil ApiKey in GoogleModel.Chat (check apiConfig != nil &&
apiConfig.ApiKey != nil and return a clear error) and avoid dereferencing
*apiConfig.ApiKey without checks; add similar guards where ApiKey is used later.
Add defensive checks on response before indexing: verify
len(response.Candidates) > 0, response.Candidates[0].Content != nil and iterate
over response.Candidates[0].Content.Parts (checking len and p.Thought) to build
ReasonContent instead of assuming Parts[0] contains a thought. Also stop
creating a genai client on every call: initialize and cache the genai.Client on
the GoogleModel receiver (lazily create it in GoogleModel.Chat using
genai.NewClient only if the cached client is nil) to reuse the client and avoid
per-request construction.
| func (z *GoogleModel) ChatStreamlyWithSender(modelName, message *string, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error { | ||
| ctx := context.Background() | ||
| client, err := genai.NewClient(ctx, &genai.ClientConfig{ | ||
| APIKey: *apiConfig.ApiKey, | ||
| Backend: genai.BackendGeminiAPI, | ||
| }) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| contents := []*genai.Content{ | ||
| genai.NewContentFromText(*message, genai.RoleUser), | ||
| } | ||
| for response, err := range client.Models.GenerateContentStream( | ||
| ctx, | ||
| *modelName, | ||
| contents, | ||
| nil, | ||
| ) { | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| content := response.Text() | ||
|
|
||
| var responseContent string | ||
| if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | ||
| responseContent = response.Candidates[0].Content.Parts[0].Text | ||
| } | ||
|
|
||
| if responseContent != "" { | ||
| logger.Info(fmt.Sprintf("Thinking: %s", responseContent)) | ||
| if err = sender(nil, &responseContent); err != nil { | ||
| return err | ||
| } | ||
| } | ||
|
|
||
| if content != "" { | ||
| logger.Info(fmt.Sprintf("Answer: %s", responseContent)) | ||
| if err = sender(&content, nil); err != nil { | ||
| return err | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return err | ||
| } |
There was a problem hiding this comment.
Several bugs in ChatStreamlyWithSender.
generateContentConfigisnil(line 108). UnlikeChat, the stream call does not pass anyGenerateContentConfig, soThinkingConfig.IncludeThoughtsis never set and thoughts will never be streamed — thechatModelConfig.Thinkingbranch on line 117 becomes dead. Build and pass the same config asChat.- Same
Parts[0]/ thought-flag bug asChat. Lines 117–119 takeParts[0].Textblindly; missing length checks and missingIsThoughtfiltering. This will misroute streamed answer chunks into the "thinking" callback. - Wrong variable in log (line 129). Logs
"Answer: %s"formatted withresponseContentinstead ofcontent. - Final
return err(line 136) is misleading. Theerrreferenced here is the outer-scope variable from thegenai.NewClientcall (line 98), which is guaranteed nil at this point — the loop-scopederrfromfor response, err := range ...is shadowed and not visible here. If the iterator's terminal error matters, you must capture it inside the loop body. Otherwise justreturn nil. - Logging full content at Info level (lines 122, 129) can leak user input/output into logs and is noisy for streaming. Consider lowering to Debug or removing.
♻️ Suggested adjustments
- for response, err := range client.Models.GenerateContentStream(
- ctx,
- *modelName,
- contents,
- nil,
- ) {
- if err != nil {
- return err
- }
-
- content := response.Text()
-
- var responseContent string
- if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
- responseContent = response.Candidates[0].Content.Parts[0].Text
- }
-
- if responseContent != "" {
- logger.Info(fmt.Sprintf("Thinking: %s", responseContent))
- if err = sender(nil, &responseContent); err != nil {
- return err
- }
- }
-
- if content != "" {
- logger.Info(fmt.Sprintf("Answer: %s", responseContent))
- if err = sender(&content, nil); err != nil {
- return err
- }
- }
- }
-
- return err
+ cfg := &genai.GenerateContentConfig{
+ ThinkingConfig: &genai.ThinkingConfig{
+ IncludeThoughts: chatModelConfig.Thinking != nil && *chatModelConfig.Thinking,
+ },
+ }
+ for response, iterErr := range client.Models.GenerateContentStream(ctx, *modelName, contents, cfg) {
+ if iterErr != nil {
+ return iterErr
+ }
+ if len(response.Candidates) == 0 || response.Candidates[0].Content == nil {
+ continue
+ }
+ var answer, thought string
+ for _, p := range response.Candidates[0].Content.Parts {
+ if p.Thought {
+ thought += p.Text
+ } else {
+ answer += p.Text
+ }
+ }
+ if thought != "" {
+ if err := sender(nil, &thought); err != nil {
+ return err
+ }
+ }
+ if answer != "" {
+ if err := sender(&answer, nil); err != nil {
+ return err
+ }
+ }
+ }
+ return nil🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/google.go` around lines 92 - 137,
ChatStreamlyWithSender has multiple bugs: create and pass a non-nil
GenerateContentConfig (same as Chat) enabling ThinkingConfig.IncludeThoughts
when chatModelConfig.Thinking is set; inside the stream loop, don't assume
Candidates/Content.Parts exist—check lengths and filter Parts by IsThought (use
response.Candidates[i].Content.Parts[j].IsThought) so thought parts go to the
thinking path and answer parts to the content path; fix the logging call to
print the actual answer variable (use content for "Answer") and lower sensitive
logs to debug; capture the loop-scoped err from the GenerateContentStream
iterator into a local variable and return that (or return nil explicitly if you
decide not to propagate iterator errors); locate fixes around
ChatStreamlyWithSender, GenerateContentConfig/ThinkingConfig,
response.Candidates/Content.Parts, response.Text, and sender.
| func (z *GoogleModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { | ||
| return nil, fmt.Errorf("no such method") | ||
| } | ||
|
|
||
| func (z *GoogleModel) CheckConnection(apiConfig *APIConfig) error { | ||
| return fmt.Errorf("no such method") | ||
| } |
There was a problem hiding this comment.
CheckConnection should not return an error for a supported provider.
Returning "no such method" will make any health/connection check fail for Google. At minimum, return nil; ideally, perform a lightweight call (e.g. client.Models.List with a small request) to validate the API key. Balance returning an error is fine since Google doesn't expose one, but CheckConnection is part of normal startup/health flow.
-func (z *GoogleModel) CheckConnection(apiConfig *APIConfig) error {
- return fmt.Errorf("no such method")
+func (z *GoogleModel) CheckConnection(apiConfig *APIConfig) error {
+ if apiConfig == nil || apiConfig.ApiKey == nil {
+ return fmt.Errorf("missing API key")
+ }
+ ctx := context.Background()
+ client, err := genai.NewClient(ctx, &genai.ClientConfig{
+ APIKey: *apiConfig.ApiKey,
+ Backend: genai.BackendGeminiAPI,
+ })
+ if err != nil {
+ return err
+ }
+ _, err = client.Models.List(ctx, &genai.ListModelsConfig{})
+ return err
}📝 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.
| func (z *GoogleModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { | |
| return nil, fmt.Errorf("no such method") | |
| } | |
| func (z *GoogleModel) CheckConnection(apiConfig *APIConfig) error { | |
| return fmt.Errorf("no such method") | |
| } | |
| func (z *GoogleModel) CheckConnection(apiConfig *APIConfig) error { | |
| if apiConfig == nil || apiConfig.ApiKey == nil { | |
| return fmt.Errorf("missing API key") | |
| } | |
| ctx := context.Background() | |
| client, err := genai.NewClient(ctx, &genai.ClientConfig{ | |
| APIKey: *apiConfig.ApiKey, | |
| Backend: genai.BackendGeminiAPI, | |
| }) | |
| if err != nil { | |
| return err | |
| } | |
| _, err = client.Models.List(ctx, &genai.ListModelsConfig{}) | |
| return err | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/entity/models/google.go` around lines 167 - 173, The CheckConnection
method on GoogleModel currently returns fmt.Errorf("no such method"), which
breaks health/startup checks; update GoogleModel.CheckConnection to return nil
for a supported provider (or preferably perform a lightweight validation by
constructing a Google client and making a minimal call such as
client.Models.List or another cheap API call to verify the API key and return
any error), while leaving Balance as-is; ensure the method uses the APIConfig
input to build the client and returns nil on success or the underlying error on
failure.
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
internal/service/model_service.go (1)
894-902: Provider-driver streaming errors are now correctly propagated to the handler.Returning
(CodeServerError, err)onChatStreamlyWithSenderfailure (line 896) and(CodeSuccess, nil)on completion (line 899) lines up with the new handler logic ininternal/handler/providers.go(lines 740-744). One nit: the terminalreturn common.CodeServerError, errors.New("model is disabled")on line 902 represents a user/configuration condition rather than a server error; consider a more semantically appropriate code (e.g.,CodeBadRequest/forbidden) — same observation applies to the analogous return inChatToModel(line 800), so feel free to defer.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/service/model_service.go` around lines 894 - 902, The final return currently uses common.CodeServerError for a user/configuration condition ("model is disabled"); change that to a more appropriate semantic code such as common.CodeBadRequest (or common.CodeForbidden if you prefer) where the function returns the error "model is disabled" (the block that calls providerInfo.ModelDriver.ChatStreamlyWithSender and the terminal return), and make the same change in the analogous return in ChatToModel so both handlers return the client/validation-level code instead of CodeServerError.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@go.mod`:
- Line 115: The go.mod currently pulls google.golang.org/grpc v1.66.2 which is
vulnerable; update the grpc module to at least v1.79.3 by replacing the version
for google.golang.org/grpc in go.mod with v1.79.3 (or later) and then run `go
mod tidy` to refresh go.sum; if the transitive dependency
google.golang.org/genai does not propagate the bump, add an explicit direct
requirement for google.golang.org/grpc v1.79.3 in go.mod to force the upgrade.
In `@internal/handler/providers.go`:
- Around line 740-745: The error SSE path from ChatToModelStreamWithSender
currently sends c.SSEvent("error", err.Error()) then returns without flushing
and assumes err is non-nil; update the handler to defensively check if err is
nil and build a safe error message (e.g., "unknown error" or include error
details if non-nil), call c.SSEvent("error", message), then explicitly flush the
response with c.Writer.Flush() (or the framework's flush) before returning to
ensure the error frame is sent to the client.
In `@internal/service/model_service.go`:
- Around line 871-881: The code reuses the DAO error from
GetModelByProviderIDAndInstanceIDAndModelName when provider lookup fails,
causing callers to see the wrong failure reason; update the branch where
providerInfo is nil (inside the block after
GetModelByProviderIDAndInstanceIDAndModelName returns an error) to return a
fresh error like errors.New("provider not found") (matching ChatToModel
behavior) instead of returning the stale err, and keep returning the actual DAO
error only for the subsequent GetModelByName call; locate symbols
GetModelByProviderIDAndInstanceIDAndModelName,
GetModelProviderManager().FindProvider, and
GetModelProviderManager().GetModelByName to apply this change.
---
Nitpick comments:
In `@internal/service/model_service.go`:
- Around line 894-902: The final return currently uses common.CodeServerError
for a user/configuration condition ("model is disabled"); change that to a more
appropriate semantic code such as common.CodeBadRequest (or common.CodeForbidden
if you prefer) where the function returns the error "model is disabled" (the
block that calls providerInfo.ModelDriver.ChatStreamlyWithSender and the
terminal return), and make the same change in the analogous return in
ChatToModel so both handlers return the client/validation-level code instead of
CodeServerError.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c951c329-3581-4777-896b-b483fee225f3
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (5)
go.modinternal/entity/models/factory.gointernal/entity/models/zhipu-ai.gointernal/handler/providers.gointernal/service/model_service.go
| golang.org/x/text v0.33.0 // indirect | ||
| google.golang.org/protobuf v1.32.0 // indirect | ||
| google.golang.org/genproto/googleapis/rpc v0.0.0-20240903143218-8af14fe29dc1 // indirect | ||
| google.golang.org/grpc v1.66.2 // indirect |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm the resolved grpc version after `go mod` resolution and surface any other vulnerable deps.
fd -t f '^go\.(mod|sum)$' --max-depth 2
rg -nP '^\s*google\.golang\.org/grpc\s+v' go.mod go.sum
# Show what currently pulls grpc in transitively (manual inspection).
rg -nP 'google\.golang\.org/grpc' go.sum | head -50Repository: infiniflow/ragflow
Length of output: 1426
🌐 Web query:
GHSA-p77j-4mvh-x3m3 gRPC grpc-go authorization bypass
💡 Result:
GHSA-p77j-4mvh-x3m3 (CVE-2026-33186) is a critical authorization bypass vulnerability (CVSS 9.1) in gRPC-Go (google.golang.org/grpc) versions prior to 1.79.3. The gRPC-Go server accepts HTTP/2 requests with a :path pseudo-header missing the leading slash (e.g., "Service/Method" instead of "/Service/Method"). It routes these to the correct handler, but authorization interceptors (e.g., grpc/authz) receive the non-canonical path, causing "deny" rules for canonical paths to fail to match. If a fallback "allow" exists, the request bypasses authorization. Impacted: gRPC-Go servers using path-based auth interceptors with specific deny rules + default allow. Exploitation: Send raw HTTP/2 frames with malformed :path directly to the server (requires network access, no auth needed). Fix: Upgrade to v1.79.3 or later, which rejects such requests with codes.Unimplemented. Mitigations: 1. Add outermost validating interceptor: func pathValidationInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if info.FullMethod == "" || info.FullMethod[0] != '/' { return nil, status.Errorf(codes.Unimplemented, "malformed method name") } return handler(ctx, req) } s := grpc.NewServer(grpc.ChainUnaryInterceptor(pathValidationInterceptor, ...other interceptors...)) 2. Configure proxies/load balancers (Envoy, NGINX) to enforce :path slash. 3. Use default-deny policies. Published March 2026.
Citations:
- 1: GHSA-p77j-4mvh-x3m3
- 2: https://cve.circl.lu/vuln/ghsa-p77j-4mvh-x3m3
- 3: https://test.osv.dev/vulnerability/GHSA-p77j-4mvh-x3m3
- 4: https://nvd.nist.gov/vuln/detail/CVE-2026-33186
- 5: GHSA-p77j-4mvh-x3m3
🌐 Web query:
CVE-2026-33186 grpc authorization bypass v1.79.3
💡 Result:
CVE-2026-33186 is a critical authorization bypass vulnerability (CVSS 9.1) in gRPC-Go versions prior to 1.79.3. It affects servers using path-based authorization interceptors (e.g., google.golang.org/grpc/authz) with policies that have specific "deny" rules for canonical paths (/Service/Method) but a fallback "allow" rule. The issue arises because the gRPC-Go server accepts HTTP/2 requests with a :path pseudo-header missing the leading slash (e.g., Service/Method). The server routes these to the correct handler, but authorization interceptors evaluate the raw non-canonical path, causing deny rules to fail to match and allowing the request if a fallback allow exists. Exploitation requires sending raw HTTP/2 frames with malformed :path directly to the server (network-accessible, no privileges needed). Fixed in v1.79.3: Requests without leading slash in :path are rejected with codes.Unimplemented before reaching interceptors/handlers. Mitigations: 1. Validating interceptor (check info.FullMethod starts with '/'): func pathValidationInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if info.FullMethod == "" || info.FullMethod[0] != '/' { return nil, status.Errorf(codes.Unimplemented, "malformed method name") } return handler(ctx, req) } Use as first interceptor: grpc.ChainUnaryInterceptor(pathValidationInterceptor, ...) 2. Infrastructure normalization (reverse proxy enforces HTTP/2 :path compliance). 3. Policy hardening (default deny, explicit allows). Upgrade to google.golang.org/grpc v1.79.3 or later. GHSA-p77j-4mvh-x3m3.
Citations:
- 1: https://nvd.nist.gov/vuln/detail/CVE-2026-33186
- 2: security: CVE-2026-33186 — google.golang.org/grpc Authorization Bypass (CVSS 9.1 Critical) DataDog/datadog-agent#48151
- 3: https://www.tenable.com/cve/CVE-2026-33186
- 4: https://nvd.nist.gov/vuln/detail/cve-2026-33186
- 5: GHSA-p77j-4mvh-x3m3
- 6: https://github.com/grpc/grpc-go/releases/tag/v1.79.3
🌐 Web query:
google.golang.org/grpc v1.66.2 vulnerability advisory
💡 Result:
There is no specific vulnerability advisory for google.golang.org/grpc v1.66.2. v1.66.2 (released around late 2024) is vulnerable to CVE-2026-33186 (GHSA-p77j-4mvh-x3m3), a critical authorization bypass in gRPC-Go servers due to improper HTTP/2 :path validation. This affects versions prior to v1.79.3, where the server accepts requests without a leading slash in the path (e.g., "Service/Method" instead of "/Service/Method"), bypassing path-based authorization interceptors like google.golang.org/grpc/authz if policies use canonical paths with a leading slash and have a fallback allow rule. The official fix is in v1.79.3 (March 2026), which rejects non-canonical paths with codes.Unimplemented. A community-requested cherry-pick to the v1.66.x branch (PR #9024, March 2026) was not merged per gRPC policy, as v1.66 is no longer supported (FAQ: https://grpc.io/docs/what-is-grpc/faq/#how-long-are-grpc-releases-supported-for). Mitigations (from advisory): 1. Validating interceptor: func pathValidationInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { if !strings.HasPrefix(info.FullMethod, "/") { return nil, status.Errorf(codes.Unimplemented, "malformed method name") } return handler(ctx, req) } s := grpc.NewServer(grpc.ChainUnaryInterceptor(pathValidationInterceptor, ...)) 2. Reverse proxy/load balancer enforcing HTTP/2 :path compliance. 3. Default-deny authorization policies. Upgrade to v1.79.3+ is recommended. No other vulnerabilities specific to v1.66.2 found; older issues like HTTP/2 Rapid Reset (GHSA-m425-mq94-257g) affect it but are not v1.66.2-specific.
Citations:
- 1: Cherry pick fix for CVE-2026-33186 for 1.66.x (grpc-ui vuln.) grpc/grpc-go#9024
- 2: https://nvd.nist.gov/vuln/detail/cve-2026-33186
- 3: https://nvd.nist.gov/vuln/detail/CVE-2026-33186
- 4: https://github.com/grpc/grpc-go/security/advisories
- 5: https://security-tracker.debian.org/tracker/CVE-2026-33186
- 6: GHSA-p77j-4mvh-x3m3
- 7: https://github.com/grpc/grpc-go/tags
Critical: gRPC-Go v1.66.2 has a known authorization-bypass CVE — upgrade to ≥ v1.79.3.
The transitively required google.golang.org/grpc v1.66.2 is affected by GHSA-p77j-4mvh-x3m3 / CVE-2026-33186 (CVSS 9.1, Critical) — an authorization bypass in gRPC-Go servers that accept HTTP/2 requests with a :path pseudo-header missing the leading slash (e.g., Service/Method instead of /Service/Method). When authorization interceptors evaluate the non-canonical path, deny rules fail to match, allowing requests to bypass authorization if a fallback allow rule exists. The fix lands in v1.79.3. Even though grpc is indirect here, the published binary will ship the vulnerable code. Upgrade to v1.79.3 or later.
Suggested fix
- google.golang.org/grpc v1.66.2 // indirect
+ google.golang.org/grpc v1.79.3 // indirectThen run go mod tidy to refresh go.sum. If google.golang.org/genai v1.54.0 does not bump grpc forward automatically, the explicit pin here will resolve it.
📝 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.
| google.golang.org/grpc v1.66.2 // indirect | |
| google.golang.org/grpc v1.79.3 // indirect |
🧰 Tools
🪛 OSV Scanner (2.3.5)
[CRITICAL] 115-115: google.golang.org/grpc 1.66.2: Authorization bypass in gRPC-Go via missing leading slash in :path in google.golang.org/grpc
(GO-2026-4762)
[CRITICAL] 115-115: google.golang.org/grpc 1.66.2: gRPC-Go has an authorization bypass via missing leading slash in :path
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@go.mod` at line 115, The go.mod currently pulls google.golang.org/grpc
v1.66.2 which is vulnerable; update the grpc module to at least v1.79.3 by
replacing the version for google.golang.org/grpc in go.mod with v1.79.3 (or
later) and then run `go mod tidy` to refresh go.sum; if the transitive
dependency google.golang.org/genai does not propagate the bump, add an explicit
direct requirement for google.golang.org/grpc v1.79.3 in go.mod to force the
upgrade.
| errorCode, err := h.modelProviderService.ChatToModelStreamWithSender(providerName, instanceName, req.ModelName, userID, req.Message, &apiConfig, &chatConfig, sender) | ||
|
|
||
| if errorCode != common.CodeSuccess { | ||
| c.SSEvent("error", "stream failed") | ||
| c.SSEvent("error", err.Error()) | ||
| } | ||
| return |
There was a problem hiding this comment.
Flush after the error SSE event, and consider a defensive nil-check on err.
Two small concerns on the streaming error path:
c.SSEvent("error", err.Error())is followed only byreturn— without an explicitc.Writer.Flush(), the error frame may be buffered and never reach the client (the success path consistently flushes after each event in thesenderclosure).- Although every non-success path in
ChatToModelStreamWithSendercurrently returns a non-nilerr, this is a behavioral coupling. A defensive nil-check would prevent a panic if that contract drifts.
🛡️ Suggested fix
if errorCode != common.CodeSuccess {
- c.SSEvent("error", err.Error())
+ msg := "stream failed"
+ if err != nil {
+ msg = err.Error()
+ }
+ c.SSEvent("error", msg)
+ c.Writer.Flush()
}
return📝 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.
| errorCode, err := h.modelProviderService.ChatToModelStreamWithSender(providerName, instanceName, req.ModelName, userID, req.Message, &apiConfig, &chatConfig, sender) | |
| if errorCode != common.CodeSuccess { | |
| c.SSEvent("error", "stream failed") | |
| c.SSEvent("error", err.Error()) | |
| } | |
| return | |
| errorCode, err := h.modelProviderService.ChatToModelStreamWithSender(providerName, instanceName, req.ModelName, userID, req.Message, &apiConfig, &chatConfig, sender) | |
| if errorCode != common.CodeSuccess { | |
| msg := "stream failed" | |
| if err != nil { | |
| msg = err.Error() | |
| } | |
| c.SSEvent("error", msg) | |
| c.Writer.Flush() | |
| } | |
| return |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/handler/providers.go` around lines 740 - 745, The error SSE path
from ChatToModelStreamWithSender currently sends c.SSEvent("error", err.Error())
then returns without flushing and assumes err is non-nil; update the handler to
defensively check if err is nil and build a safe error message (e.g., "unknown
error" or include error details if non-nil), call c.SSEvent("error", message),
then explicitly flush the response with c.Writer.Flush() (or the framework's
flush) before returning to ensure the error frame is sent to the client.
| _, err = m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(provider.ID, instance.ID, modelName) | ||
| if err != nil { | ||
| providerInfo := dao.GetModelProviderManager().FindProvider(providerName) | ||
| if providerInfo == nil { | ||
| return common.CodeNotFound | ||
| return common.CodeNotFound, err | ||
| } | ||
|
|
||
| _, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName) | ||
| if err != nil { | ||
| return common.CodeNotFound | ||
| return common.CodeNotFound, err | ||
| } |
There was a problem hiding this comment.
Error returned at line 875 misrepresents the failure cause.
When GetModelByProviderIDAndInstanceIDAndModelName errors (model is not in the disabled list — the "enabled" path), err is then reused at line 875. If providerInfo == nil, you return that stale err (the disabled-list lookup error) along with CodeNotFound, which surfaces a confusing message to callers (the real cause is "provider not found", not a DAO miss on the disabled-models table).
The companion ChatToModel function at line 770 correctly returns errors.New("provider not found") here. Mirror that for consistency.
🛠️ Suggested fix
_, err = m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(provider.ID, instance.ID, modelName)
if err != nil {
providerInfo := dao.GetModelProviderManager().FindProvider(providerName)
if providerInfo == nil {
- return common.CodeNotFound, err
+ return common.CodeNotFound, errors.New("provider not found")
}
_, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName)
if err != nil {
- return common.CodeNotFound, err
+ return common.CodeNotFound, fmt.Errorf("provider %s model %s not found", providerName, modelName)
}📝 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.
| _, err = m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(provider.ID, instance.ID, modelName) | |
| if err != nil { | |
| providerInfo := dao.GetModelProviderManager().FindProvider(providerName) | |
| if providerInfo == nil { | |
| return common.CodeNotFound | |
| return common.CodeNotFound, err | |
| } | |
| _, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName) | |
| if err != nil { | |
| return common.CodeNotFound | |
| return common.CodeNotFound, err | |
| } | |
| _, err = m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(provider.ID, instance.ID, modelName) | |
| if err != nil { | |
| providerInfo := dao.GetModelProviderManager().FindProvider(providerName) | |
| if providerInfo == nil { | |
| return common.CodeNotFound, errors.New("provider not found") | |
| } | |
| _, err = dao.GetModelProviderManager().GetModelByName(providerName, modelName) | |
| if err != nil { | |
| return common.CodeNotFound, fmt.Errorf("provider %s model %s not found", providerName, modelName) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/service/model_service.go` around lines 871 - 881, The code reuses
the DAO error from GetModelByProviderIDAndInstanceIDAndModelName when provider
lookup fails, causing callers to see the wrong failure reason; update the branch
where providerInfo is nil (inside the block after
GetModelByProviderIDAndInstanceIDAndModelName returns an error) to return a
fresh error like errors.New("provider not found") (matching ChatToModel
behavior) instead of returning the stale err, and keep returning the actual DAO
error only for the subsequent GetModelByName call; locate symbols
GetModelByProviderIDAndInstanceIDAndModelName,
GetModelProviderManager().FindProvider, and
GetModelProviderManager().GetModelByName to apply this change.
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/entity/model.go (1)
522-532:⚠️ Potential issue | 🟡 MinorVerify intent: output key
clear_reasoningmismatches input/internal nameclear_thinking.The function outputs
thinking.clear_reasoningbut the input config and internal struct both useclear_thinking. No other usages ofclear_reasoningwere found in the codebase, and no comment explains whether this rename is intentional. If it is, add a comment noting the intentional output mapping. Otherwise, unify onclear_thinkingfor consistency.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@internal/entity/model.go` around lines 522 - 532, The output key for the thinking feature is inconsistent: ConvertToFeaturesMap currently emits "clear_reasoning" while the Model.Thinking field and internal config use ClearThinking/clear_thinking; update ConvertToFeaturesMap to emit "clear_thinking" (or if the rename to "clear_reasoning" is intentional, add a clear inline comment above the mapping explaining the deliberate output mapping) so the key matches the internal field name; locate ConvertToFeaturesMap and the Model.Thinking struct to make the change and ensure any downstream consumers expect the corrected key.
🧹 Nitpick comments (1)
conf/models/zhipu-ai.json (1)
21-158: Per-modelthinkingmigration LGTM.The blocks are uniform and align with the new
ModelThinkingschema ininternal/entity/model.go. As a minor follow-up: since every glm-4.5/4.6/4.7/5 entry uses an identical{default_value: true, clear_thinking: true}block, you might consider a small helper or shared default in code if this list keeps growing — not blocking.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@conf/models/zhipu-ai.json` around lines 21 - 158, Many model entries (e.g., "glm-4.5", "glm-4.6", "glm-4.7", "glm-5-turbo") repeat the identical thinking block {default_value: true, clear_thinking: true}; update the configuration to avoid duplication by introducing a shared default (or factory/helper) for ModelThinking and reuse it for those models — implement the shared default in the code that loads/parses conf/models/zhipu-ai.json (referencing the ModelThinking type in internal/entity/model.go) or refactor the config loader to inject a common thinking object for matching model names so the repeated blocks are centralized and maintained in one place.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@conf/models/zhipu-ai.json`:
- Around line 82-93: The model entry's "name" field currently uses incorrect
casing ("glm-4.6v-Flash") which will be sent verbatim to the upstream
Zhipu/Bigmodel API; change the "name" value to the lowercase canonical
identifier "glm-4.6v-flash" in the JSON object (the entry containing "name":
"glm-4.6v-Flash" with the accompanying "max_tokens" and "thinking" block) so it
matches other flash variants and the API spec.
---
Outside diff comments:
In `@internal/entity/model.go`:
- Around line 522-532: The output key for the thinking feature is inconsistent:
ConvertToFeaturesMap currently emits "clear_reasoning" while the Model.Thinking
field and internal config use ClearThinking/clear_thinking; update
ConvertToFeaturesMap to emit "clear_thinking" (or if the rename to
"clear_reasoning" is intentional, add a clear inline comment above the mapping
explaining the deliberate output mapping) so the key matches the internal field
name; locate ConvertToFeaturesMap and the Model.Thinking struct to make the
change and ensure any downstream consumers expect the corrected key.
---
Nitpick comments:
In `@conf/models/zhipu-ai.json`:
- Around line 21-158: Many model entries (e.g., "glm-4.5", "glm-4.6", "glm-4.7",
"glm-5-turbo") repeat the identical thinking block {default_value: true,
clear_thinking: true}; update the configuration to avoid duplication by
introducing a shared default (or factory/helper) for ModelThinking and reuse it
for those models — implement the shared default in the code that loads/parses
conf/models/zhipu-ai.json (referencing the ModelThinking type in
internal/entity/model.go) or refactor the config loader to inject a common
thinking object for matching model names so the repeated blocks are centralized
and maintained in one place.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e408cde0-c320-4f23-9607-b323048aaea1
📒 Files selected for processing (8)
conf/models/deepseek.jsonconf/models/gitee.jsonconf/models/google.jsonconf/models/minimax.jsonconf/models/moonshot.jsonconf/models/siliconflow.jsonconf/models/zhipu-ai.jsoninternal/entity/model.go
✅ Files skipped from review due to trivial changes (3)
- conf/models/siliconflow.json
- conf/models/gitee.json
- conf/models/google.json
| { | ||
| "name": "glm-4.6v-Flash", | ||
| "max_tokens": 131072, | ||
| "model_types": [ | ||
| "chat", | ||
| "vision" | ||
| ] | ||
| ], | ||
| "thinking": { | ||
| "default_value": true, | ||
| "clear_thinking": true | ||
| } | ||
| }, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, let's check the actual file content around the specified lines
cat -n conf/models/zhipu-ai.json | sed -n '78,95p'Repository: infiniflow/ragflow
Length of output: 524
🏁 Script executed:
# Search for any references to glm-4.6v in the codebase to see how it's used
rg "glm-4\.6v" -iRepository: infiniflow/ragflow
Length of output: 272
🏁 Script executed:
# Check all model names in this config file to understand the naming pattern
rg '"name":\s*"glm' conf/models/zhipu-ai.jsonRepository: infiniflow/ragflow
Length of output: 800
🌐 Web query:
Zhipu Bigmodel glm-4.6v official model name capitalization API documentation
💡 Result:
The official model name for Zhipu AI's (also known as Zhipu BigModel) GLM-4.6V is "GLM-4.6V", with the API identifier "glm-4.6v" (all lowercase).
Citations:
- 1: https://docs.bigmodel.cn/cn/guide/models/vlm/glm-4.6v
- 2: https://docs.z.ai/guides/vlm/glm-4.6v
- 3: https://aimodelapis.com/providers/zhipuai/zhipuai-glm-4-6v
- 4: https://github.com/zai-org/GLM-V
- 5: https://docs.bigmodel.cn/api-reference/
Change glm-4.6v-Flash to glm-4.6v-flash (lowercase).
The model name is inconsistent with both the file's other flash variants (glm-4.5-flash, glm-4-flash, glm-4.7-flashx) and the official Zhipu/Bigmodel API documentation, which specifies the canonical identifier as glm-4.6v (all lowercase). Since this string is sent verbatim to the upstream API, the casing mismatch will cause an unknown-model error at request time.
Fix
- "name": "glm-4.6v-Flash",
+ "name": "glm-4.6v-flash",📝 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.
| { | |
| "name": "glm-4.6v-Flash", | |
| "max_tokens": 131072, | |
| "model_types": [ | |
| "chat", | |
| "vision" | |
| ] | |
| ], | |
| "thinking": { | |
| "default_value": true, | |
| "clear_thinking": true | |
| } | |
| }, | |
| { | |
| "name": "glm-4.6v-flash", | |
| "max_tokens": 131072, | |
| "model_types": [ | |
| "chat", | |
| "vision" | |
| ], | |
| "thinking": { | |
| "default_value": true, | |
| "clear_thinking": true | |
| } | |
| }, |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@conf/models/zhipu-ai.json` around lines 82 - 93, The model entry's "name"
field currently uses incorrect casing ("glm-4.6v-Flash") which will be sent
verbatim to the upstream Zhipu/Bigmodel API; change the "name" value to the
lowercase canonical identifier "glm-4.6v-flash" in the JSON object (the entry
containing "name": "glm-4.6v-Flash" with the accompanying "max_tokens" and
"thinking" block) so it matches other flash variants and the API spec.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14395 +/- ##
=======================================
Coverage 95.30% 95.30%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 670 670
Misses 16 16
Partials 17 17 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
As title.
Type of change