Skip to content

Go: add new provider: google - #14395

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
JinHai-CN:fix399
Apr 27, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
JinHai-CN:fix399

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

What problem does this PR solve?

As title.

Type of change

  • New Feature (non-breaking change which adds functionality)

@coderabbitai

coderabbitai Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds 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

Cohort / File(s) Summary
Google provider
conf/models/google.json, internal/entity/models/google.go
New Google model config (gemini-2.5-flash) and GoogleModel driver: synchronous Chat, streaming ChatStreamlyWithSender, ListModels, and stubs for messages/embeddings, Balance, CheckConnection.
Dependency updates
go.mod
Adds google.golang.org/genai v1.54.0 and related Google/protobuf/grpc/otel indirect deps and bumps protobuf/otel versions.
Factory wiring
internal/entity/models/factory.go
Factory now recognizes provider "google" (case-insensitive) and returns the GoogleModel driver.
Service & handler streaming flow
internal/service/model_service.go, internal/handler/providers.go
ChatToModelStreamWithSender now returns (errorCode, error); underlying errors are propagated and handler sends streaming error text from err.Error().
Model thinking representation
internal/entity/model.go, conf/models/*.json
Renamed clear_content → clear_thinking, removed provider-level features.thinking in multiple configs and moved thinking/clear_thinking into per-model entries (several conf/models/*.json updated).
Other drivers
internal/entity/models/zhipu-ai.go
Adjusted streaming delta emission order: reasoning_content emitted before content; minor request-body formatting tweak.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

💞 feature

Poem

🐇 Hopped into code with a curious twitch,
I wired Gemini's stream and fetched a stitch.
Thoughts came first, then answers in light—
The warren now chats through day and night.
🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

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.
Description check ❓ Inconclusive The description is minimal and follows the template structure but lacks substantive detail about the implementation, scope of changes, or rationale beyond restating the title. Expand the description to explain what the Google provider enables, which models are supported, key implementation details, and any relevant context about why this addition is needed.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the primary change: adding support for a new Google provider in the Go codebase, which is reflected across the configuration and implementation files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@JinHai-CN JinHai-CN added the ci Continue Integration label Apr 27, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review April 27, 2026 06:51
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 27, 2026

@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: 7

🧹 Nitpick comments (2)
internal/entity/models/google.go (2)

60-66: Simplify ThinkingConfig setup.

The else branch is redundant — IncludeThoughts defaults 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.List returns paginated results via Page[Model]. The current code only processes the first page (models.Items), missing remaining results when a NextPageToken exists. Additionally, the Gemini API returns all models including embeddings and legacy variants, but the use case is chat-only. Use modelsPage.all(ctx) to iterate all pages, and filter by checking each model's SupportedActions field 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0b46ab0 and 05c096b.

📒 Files selected for processing (2)
  • conf/models/google.json
  • internal/entity/models/google.go

Comment thread conf/models/google.json
Comment on lines +26 to +31
"reasoning_effort": {
"default_value": "high",
"supported_modes": [
"gemini-2.5-flash"
]
}

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 | 🟠 Major

🧩 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.go

Repository: 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 -20

Repository: 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 -60

Repository: 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.

Suggested change
"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).

Comment thread internal/entity/models/google.go Resolved
Comment thread internal/entity/models/google.go Resolved
"google.golang.org/genai"
)

// GoogleModel implements ModelDriver for Dummy AI

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 | 🟡 Minor

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.

Suggested change
// 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.

Comment on lines +46 to +84
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
}

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 | 🔴 Critical

🧩 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:


Multiple correctness issues in Chat.

  1. Nil-pointer deref on *apiConfig.ApiKey (line 49). No guard for apiConfig == nil or apiConfig.ApiKey == nil; an empty/missing key will panic instead of returning a clean error. Same issue at lines 95 and 147.

  2. response.Candidates[0].Content.Parts[0].Text (line 76) is unsafe. No length checks on Candidates or Parts — the API may return an empty list (e.g., blocked/filtered response), causing a panic.

  3. Unsafe thought extraction (line 76). When thinking is enabled, the code assumes Parts[0] is a thought part, but doesn't verify this. Since response.Text() returns only non-thought parts, the thought text must be extracted by iterating Parts and checking each part.Thought == true. As written, ReasonContent may contain answer text or nothing if the first part is not a thought.

  4. Client is constructed on every call. genai.NewClient should 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.

Comment on lines +92 to +137
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
}

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 | 🔴 Critical

Several bugs in ChatStreamlyWithSender.

  1. generateContentConfig is nil (line 108). Unlike Chat, the stream call does not pass any GenerateContentConfig, so ThinkingConfig.IncludeThoughts is never set and thoughts will never be streamed — the chatModelConfig.Thinking branch on line 117 becomes dead. Build and pass the same config as Chat.
  2. Same Parts[0] / thought-flag bug as Chat. Lines 117–119 take Parts[0].Text blindly; missing length checks and missing IsThought filtering. This will misroute streamed answer chunks into the "thinking" callback.
  3. Wrong variable in log (line 129). Logs "Answer: %s" formatted with responseContent instead of content.
  4. Final return err (line 136) is misleading. The err referenced here is the outer-scope variable from the genai.NewClient call (line 98), which is guaranteed nil at this point — the loop-scoped err from for 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 just return nil.
  5. 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.

Comment on lines +167 to +173
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")
}

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 | 🟠 Major

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.

Suggested change
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.

@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: 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) on ChatStreamlyWithSender failure (line 896) and (CodeSuccess, nil) on completion (line 899) lines up with the new handler logic in internal/handler/providers.go (lines 740-744). One nit: the terminal return 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 in ChatToModel (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

📥 Commits

Reviewing files that changed from the base of the PR and between 05c096b and 1747810.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (5)
  • go.mod
  • internal/entity/models/factory.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/providers.go
  • internal/service/model_service.go

Comment thread go.mod
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

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 | 🔴 Critical

🧩 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 -50

Repository: 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:


🌐 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:


🌐 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:


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 // indirect

Then 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.

Suggested change
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

(GHSA-p77j-4mvh-x3m3)

🤖 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.

Comment on lines +740 to 745
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

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 | 🟡 Minor

Flush after the error SSE event, and consider a defensive nil-check on err.

Two small concerns on the streaming error path:

  1. c.SSEvent("error", err.Error()) is followed only by return — without an explicit c.Writer.Flush(), the error frame may be buffered and never reach the client (the success path consistently flushes after each event in the sender closure).
  2. Although every non-success path in ChatToModelStreamWithSender currently returns a non-nil err, 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.

Suggested change
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.

Comment on lines 871 to 881
_, 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
}

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 | 🟡 Minor

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.

Suggested change
_, 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.

@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

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 | 🟡 Minor

Verify intent: output key clear_reasoning mismatches input/internal name clear_thinking.

The function outputs thinking.clear_reasoning but the input config and internal struct both use clear_thinking. No other usages of clear_reasoning were 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 on clear_thinking for 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-model thinking migration LGTM.

The blocks are uniform and align with the new ModelThinking schema in internal/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

📥 Commits

Reviewing files that changed from the base of the PR and between 1747810 and 0d682e1.

📒 Files selected for processing (8)
  • conf/models/deepseek.json
  • conf/models/gitee.json
  • conf/models/google.json
  • conf/models/minimax.json
  • conf/models/moonshot.json
  • conf/models/siliconflow.json
  • conf/models/zhipu-ai.json
  • internal/entity/model.go
✅ Files skipped from review due to trivial changes (3)
  • conf/models/siliconflow.json
  • conf/models/gitee.json
  • conf/models/google.json

Comment thread conf/models/zhipu-ai.json
Comment on lines 82 to 93
{
"name": "glm-4.6v-Flash",
"max_tokens": 131072,
"model_types": [
"chat",
"vision"
]
],
"thinking": {
"default_value": true,
"clear_thinking": true
}
},

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 | 🟡 Minor

🧩 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" -i

Repository: 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.json

Repository: 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:


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.

Suggested change
{
"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

codecov Bot commented Apr 27, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (6a23dfe) to head (0d682e1).
⚠️ Report is 13 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot mentioned this pull request May 29, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant