Skip to content

Simplify chat and support multimodal chat - #14523

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
qinling0210:simplify_chat
Apr 30, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
qinling0210:simplify_chat

Conversation

@qinling0210

@qinling0210 qinling0210 commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Simplify chat and support multimodal chat

Type of change

  • Refactoring

@qinling0210 qinling0210 self-assigned this Apr 30, 2026
@qinling0210 qinling0210 added the ci Continue Integration label Apr 30, 2026
@qinling0210
qinling0210 marked this pull request as ready for review April 30, 2026 05:49
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Apr 30, 2026
@coderabbitai

coderabbitai Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Standardizes chat to multi-message flow: replaces single-message Chat with ChatWithMessages across drivers and types, generalizes Message content to interface{}, changes driver signatures to accept *APIConfig and return *ChatResponse, and updates CLI/handler/service to send/receive message arrays; minor HTTP error-body handling added.

Changes

Cohort / File(s) Summary
HTTP Client
internal/cli/http_client.go
Include response body text in non-OK HTTP error messages; ensure resp.Body consumed and closed before returning error.
CLI
internal/cli/user_command.go
Use fixed "/chat/completions" endpoint, trim input, allow JSON-array messages as content, send messages array payload.
Model Types
internal/entity/models/types.go
Message.Content -> interface{} with JSON tags; ModelDriver.ChatWithMessages signature updated to accept *APIConfig and return *ChatResponse.
Model Drivers — implemented/updated
internal/entity/models/...
aliyun.go, deepseek.go, gitee.go, google.go, minimax.go, moonshot.go, siliconflow.go, vllm.go, volcengine.go, zhipu-ai.go
Removed single-message Chat methods; added/implemented ChatWithMessages across drivers: validate inputs, map messages→API payloads, conditional APIConfig/chatModelConfig handling, perform HTTP/SDK calls, parse responses into *ChatResponse (Answer and optional ReasonContent).
Dummy Model
internal/entity/models/dummy.go
Removed old Chat; updated ChatWithMessages stub signature to new (*APIConfig, *ChatConfig) (*ChatResponse, error) pattern (still unimplemented).
Handler / API layer
internal/handler/providers.go
Request contract changed from message string → messages []map[string]interface{}; streaming disallows multimodal (array) content; streaming uses first message content; non-streaming maps messages → []models.Message and calls ChatWithMessages.
Service / Orchestration
internal/service/model_service.go, internal/service/chat_session.go
Service methods renamed/updated to accept []Message and call driver ChatWithMessages; ensure non-nil APIConfig defaults; filter out system/empty messages; adapt to *ChatResponse results.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as Client (CLI)
    participant Handler as HTTP Handler
    participant Service as Model Service
    participant Driver as Model Driver
    participant HTTP as HTTP Client
    participant API as External Model API

    CLI->>Handler: POST /chat (messages[])
    Handler->>Service: ChatToModelWithMessages(messages[])
    Service->>Driver: ChatWithMessages(APIConfig, messages[], ChatConfig)
    Driver->>HTTP: build request (messages, headers)
    HTTP->>API: POST /chat/completions
    API-->>HTTP: 200 + body
    HTTP-->>Driver: parsed response
    Driver-->>Service: *ChatResponse (Answer, ReasonContent)
    Service-->>Handler: structured response
    Handler-->>CLI: JSON {answer, reasoning_content}
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

☯️ refactor

Poem

🐰 A rabbit hops through code and queues,
Messages bundled in multimodal hues,
Drivers march in a tidy parade,
APIs talk in a unified braid,
Hooray — my carrots earned their dues! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The PR description covers the required template sections but lacks detailed context and explanation about the actual implementation changes and their impact. Expand the description to explain how the chat API is simplified, what multimodal support entails, and key breaking changes in the refactoring (e.g., Chat method removal, ChatWithMessages adoption).
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Simplify chat and support multimodal chat' directly and accurately describes the two main objectives of the PR: consolidating chat APIs and adding multimodal message support.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

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

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/entity/models/gitee.go (1)

87-124: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't log raw prompts or serialized request bodies.

These logger.Info calls dump every message and the full JSON payload, which can include user prompts, attachments, and data-URI image content. This is a privacy/compliance risk on a hot path.

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

In `@internal/entity/models/gitee.go` around lines 87 - 124, The code is logging
raw prompts and the full serialized request body via logger.Info when building
the Gitee API request (see variables apiMessages, reqBody, jsonData, modelName,
chatModelConfig); remove or replace these calls so no user content or
data-URI/image content is written to logs — instead log only non-sensitive
metadata (e.g., modelName, whether stream is enabled, sizes/counts like
len(apiMessages) or len(jsonData), and presence of optional fields from
chatModelConfig) or redact message content before logging; update the
logger.Info calls around the request construction to emit only that sanitized
metadata or remove them entirely.
internal/handler/providers.go (1)

829-880: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Validate messages before the streaming path indexes it.

Line 880 will panic when messages is omitted or empty, and the direct .(string) assertion will also panic if the first item is not plain text. Reject those shapes before entering the stream branch.

Suggested fix
 	// Check if it's a stream request
 	if req.Stream {
+		if len(req.Messages) == 0 {
+			c.JSON(http.StatusBadRequest, gin.H{
+				"code":    400,
+				"message": "messages is required",
+			})
+			return
+		}
+
 		// Streaming with multimodal messages not yet supported
 		hasMultimodal := false
 		for _, msg := range req.Messages {
 			if content, ok := msg["content"]; ok {
 				if _, isArray := content.([]interface{}); isArray {
@@
 			return nil
 		}
 
+		firstContent, ok := req.Messages[0]["content"].(string)
+		if !ok {
+			c.JSON(http.StatusBadRequest, gin.H{
+				"code":    400,
+				"message": "streaming currently requires the first message content to be a string",
+			})
+			return
+		}
+
 		// Stream response using sender function (best performance, no channel)
-		errorCode, err := h.modelProviderService.ChatToModelStreamWithSender(*req.ProviderName, *req.InstanceName, *req.ModelName, userID, req.Messages[0]["content"].(string), &apiConfig, &chatConfig, sender)
+		errorCode, err := h.modelProviderService.ChatToModelStreamWithSender(*req.ProviderName, *req.InstanceName, *req.ModelName, userID, firstContent, &apiConfig, &chatConfig, sender)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/handler/providers.go` around lines 829 - 880, The streaming branch
currently indexes req.Messages[0] and does a direct .(string) assertion which
can panic if Messages is nil/empty or the content is not a plain string; before
entering the stream path (before creating sender and calling
ChatToModelStreamWithSender) validate that req.Messages is non-nil and has
length > 0, verify the first message contains a "content" key, and use a safe
type assertion (value, ok := msg["content"].(string)) to ensure it's a string
(return HTTP 400 with a clear error when these checks fail); update the checks
referenced around req.Messages and the call to
h.modelProviderService.ChatToModelStreamWithSender so the call receives a
validated string.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/cli/user_command.go`:
- Around line 1548-1578: The current heuristic blindly treats any message
starting with { } or [ ] as structured multimodal content by using
json.RawMessage(message), which passes malformed JSON through and misformats
literal JSON/code prompts; change the logic in the message formatting (where
formattedMessage is built) to attempt to unmarshal message into the exact
supported multimodal shape (e.g., try json.Unmarshal into
[]map[string]interface{} or a strict struct matching the expected
array-of-content-items shape), verify that the resulting value matches the
required fields/array shape, and only then set "content" to the parsed JSON (as
a proper value); otherwise fall back to keeping content as the original string
(not json.RawMessage) so literal JSON/code stays verbatim and malformed JSON is
rejected rather than forwarded. Ensure any JSON parsing errors prevent
auto-promotion and that formattedMessage remains a string entry (role:user,
content: message).

In `@internal/entity/models/deepseek.go`:
- Around line 113-142: The code dereferences chatModelConfig.Effort inside the
Thinking branch which can panic when Effort is nil; update the logic in the
function handling the Thinking branch (where chatModelConfig.Thinking is
checked) to first guard for chatModelConfig.Effort == nil and either return a
clear validation error (e.g., fmt.Errorf("effort is required when thinking is
enabled")) or assign a safe default value before switching, then proceed with
the existing switch on *chatModelConfig.Effort (referencing
chatModelConfig.Thinking and chatModelConfig.Effort to locate the block).

In `@internal/entity/models/gitee.go`:
- Around line 97-117: The sync path dropped the "thinking" flag and now returns
raw <think> markers; update the request build in ChatStreamlyWithSender (and the
non-streaming counterpart used at lines ~175-177) to include the thinking value
when present (e.g., if chatModelConfig.Thinking != nil set reqBody["thinking"] =
*chatModelConfig.Thinking) and ensure outgoing and returned messages strip the
<think>...<\/think> markers from message.content (for streaming, emit cleaned
chunks; for non-streaming, sanitize the final Answer before returning) so
reasoning separation is preserved and no raw tags leak.

In `@internal/entity/models/google.go`:
- Around line 67-107: The multimodal handling flattens message boundaries by
appending each multimodal item as its own genai.Content and incorrectly uses
genai.NewContentFromText for image URLs; instead, for each message in the
messages loop build a slice of genai.Part objects (use
genai.NewPartFromText(...) for text parts and genai.NewPartFromURI(...) for
image_url parts), then create a single genai.Content for that message with
genai.NewContentFromParts(parts, role) and append that Content to contents
(replace the current per-item append logic that uses genai.NewContentFromText
for images); keep the role mapping logic as-is and continue to pass the
resulting contents slice to client.Models.GenerateContent.

In `@internal/entity/models/minimax.go`:
- Around line 187-190: The code dereferences apiConfig (apiConfig.Region and
apiConfig.ApiKey) without checking for nil; update the logic around the region
variable and any ApiKey usage to first guard apiConfig: if apiConfig != nil &&
apiConfig.Region != nil { region = *apiConfig.Region } else keep default, and
for ApiKey access validate apiConfig != nil && apiConfig.ApiKey != nil and
return a clear error (or handle missing key) instead of dereferencing; locate
uses of apiConfig.Region, the region variable assignment, and any code reading
apiConfig.ApiKey in minimax.go and apply these nil checks and early-return error
handling.

In `@internal/entity/models/siliconflow.go`:
- Around line 115-135: The request never forwards chatModelConfig.Thinking, so
responses expecting reasoning (ReasonContent/thinking) will not be enabled;
update the reqBody construction in the block that handles chatModelConfig to
check chatModelConfig.Thinking and, if non-nil, set reqBody["thinking"] =
*chatModelConfig.Thinking (matching the existing pointer-unwrapping pattern) so
the server is asked for reasoning-enabled replies and the downstream handling of
ReasonContent (lines around 191–207) can work correctly.

In `@internal/entity/models/vllm.go`:
- Around line 205-207: Guard against nil pointers before dereferencing apiConfig
and chatModelConfig: check that apiConfig != nil before accessing
apiConfig.Region and apiConfig.ApiKey (use a safe default like "default" for
region and empty string or a configured fallback for apikey), and check
chatModelConfig != nil before using chatModelConfig.ModelClass (use a
default/model class fallback). Apply the same nil checks and safe-default logic
to the other occurrences mentioned (around the blocks handling
apiConfig.Region/apiConfig.ApiKey at lines ~273-275 and
chatModelConfig.ModelClass at ~317) so callers that pass nil pointers do not
panic.
- Around line 205-210: ChatWithMessages constructs the request URL
unconditionally using z.URLSuffix.Chat which breaks the existing routing that
VllmModel.Chat enforces for qwen/glm models to use z.URLSuffix.AsyncChat; update
the URL construction in ChatWithMessages (the region selection using
apiConfig.Region and the fmt.Sprintf(...) that builds url) to apply the same
routing logic as VllmModel.Chat: detect qwen/glm models and switch the suffix to
z.URLSuffix.AsyncChat for those cases, otherwise use z.URLSuffix.Chat,
preserving the region handling and reusing the same model-identification check
from VllmModel.Chat.

In `@internal/entity/models/volcengine.go`:
- Around line 219-221: In ChatWithMessages, avoid nil dereferences by guarding
any optional pointer fields before use: check if apiConfig != nil before reading
apiConfig.Region and fall back to the default region string when nil; likewise
check chatModelConfig != nil and chatModelConfig.Effort != nil before
dereferencing and use a sensible default effort value when absent. Update all
occurrences in ChatWithMessages that currently do unconditional dereferences
(including the blocks around the region handling and the effort usage) to
perform nil-checks and apply defaults so local/no-auth calls or thinking
requests without explicit effort will not panic.

In `@internal/handler/providers.go`:
- Around line 879-880: The streaming call currently forwards only
req.Messages[0]["content"] to h.modelProviderService.ChatToModelStreamWithSender
which drops prior turns and later messages; change the argument to pass the full
conversation used by the non-streaming path (e.g., the messages slice or the
already-built `messages` variable) so ChatToModelStreamWithSender receives the
complete conversation context rather than just the first message content.

In `@internal/service/model_service.go`:
- Around line 729-730: The call to providerInfo.ModelDriver.ChatWithMessages
(and other similar calls around the ChatWithMessages handling) can return a nil
or empty response but the code immediately uses response.Answer, risking a
panic; update the handlers that call ChatWithMessages (references:
providerInfo.ModelDriver.ChatWithMessages, variables named response and
modelConfig) to validate that response is non-nil and that response.Answer (or
any nested fields you access) is non-nil/has expected data before returning
success — if validation fails, return a descriptive error (or wrap the original
err if present) instead of proceeding to read fields; apply the same nil-check
pattern to the other occurrences noted (around the blocks at 762-763 and
784-790).
- Line 678: The function ChatToModelWithMessages may dereference apiConfig and
modelConfig without nil checks; before any mutations or field access in
ChatToModelWithMessages, ensure both pointers are initialized when nil (e.g., if
apiConfig == nil { apiConfig = &modelModule.APIConfig{} } and similarly for
modelConfig = &modelModule.ChatConfig{}) so subsequent assignments and reads
elsewhere in the function (references to apiConfig and modelConfig inside
ChatToModelWithMessages) cannot panic; apply this initialization near the start
of the function before any modification or use.

---

Outside diff comments:
In `@internal/entity/models/gitee.go`:
- Around line 87-124: The code is logging raw prompts and the full serialized
request body via logger.Info when building the Gitee API request (see variables
apiMessages, reqBody, jsonData, modelName, chatModelConfig); remove or replace
these calls so no user content or data-URI/image content is written to logs —
instead log only non-sensitive metadata (e.g., modelName, whether stream is
enabled, sizes/counts like len(apiMessages) or len(jsonData), and presence of
optional fields from chatModelConfig) or redact message content before logging;
update the logger.Info calls around the request construction to emit only that
sanitized metadata or remove them entirely.

In `@internal/handler/providers.go`:
- Around line 829-880: The streaming branch currently indexes req.Messages[0]
and does a direct .(string) assertion which can panic if Messages is nil/empty
or the content is not a plain string; before entering the stream path (before
creating sender and calling ChatToModelStreamWithSender) validate that
req.Messages is non-nil and has length > 0, verify the first message contains a
"content" key, and use a safe type assertion (value, ok :=
msg["content"].(string)) to ensure it's a string (return HTTP 400 with a clear
error when these checks fail); update the checks referenced around req.Messages
and the call to h.modelProviderService.ChatToModelStreamWithSender so the call
receives a validated string.
🪄 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: 42f1a3cf-275f-421c-adec-5b1a960e323b

📥 Commits

Reviewing files that changed from the base of the PR and between 4ee0702 and 88f137e.

📒 Files selected for processing (17)
  • internal/cli/http_client.go
  • internal/cli/user_command.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/gitee.go
  • internal/entity/models/google.go
  • internal/entity/models/minimax.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/entity/models/vllm.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/providers.go
  • internal/service/chat_session.go
  • internal/service/model_service.go

Comment thread internal/cli/user_command.go Resolved
Comment thread internal/entity/models/deepseek.go Resolved
Comment thread internal/entity/models/gitee.go Resolved
Comment thread internal/entity/models/minimax.go Resolved
Comment on lines +115 to 135
if chatModelConfig != nil {
if chatModelConfig.Stream != nil {
reqBody["stream"] = *chatModelConfig.Stream
}

if chatModelConfig.Temperature != nil {
reqBody["temperature"] = *chatModelConfig.Temperature
}
if chatModelConfig.MaxTokens != nil {
reqBody["max_tokens"] = *chatModelConfig.MaxTokens
}

if chatModelConfig.TopP != nil {
reqBody["top_p"] = *chatModelConfig.TopP
}
if chatModelConfig.Temperature != nil {
reqBody["temperature"] = *chatModelConfig.Temperature
}

if chatModelConfig.Stop != nil {
reqBody["stop"] = *chatModelConfig.Stop
}
if chatModelConfig.TopP != nil {
reqBody["top_p"] = *chatModelConfig.TopP
}

if chatModelConfig.Thinking != nil {
if *chatModelConfig.Thinking {
reqBody["thinking"] = map[string]interface{}{
"type": "enabled",
}
} else {
reqBody["thinking"] = map[string]interface{}{
"type": "disabled",
}
if chatModelConfig.Stop != nil {
reqBody["stop"] = *chatModelConfig.Stop
}
}

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 | ⚡ Quick win

thinking is read from the response, but never requested.

Line 192 assumes a thinking-enabled reply may contain reasoning_content, but the request body above never forwards chatModelConfig.Thinking. Sync calls with thinking enabled will therefore behave like normal calls and typically never populate ReasonContent.

Also applies to: 191-207

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

In `@internal/entity/models/siliconflow.go` around lines 115 - 135, The request
never forwards chatModelConfig.Thinking, so responses expecting reasoning
(ReasonContent/thinking) will not be enabled; update the reqBody construction in
the block that handles chatModelConfig to check chatModelConfig.Thinking and, if
non-nil, set reqBody["thinking"] = *chatModelConfig.Thinking (matching the
existing pointer-unwrapping pattern) so the server is asked for
reasoning-enabled replies and the downstream handling of ReasonContent (lines
around 191–207) can work correctly.

Comment thread internal/entity/models/vllm.go Resolved
Comment thread internal/entity/models/volcengine.go Resolved
Comment on lines 879 to +880
// Stream response using sender function (best performance, no channel)
errorCode, err := h.modelProviderService.ChatToModelStreamWithSender(*req.ProviderName, *req.InstanceName, *req.ModelName, userID, req.Message, &apiConfig, &chatConfig, sender)
errorCode, err := h.modelProviderService.ChatToModelStreamWithSender(*req.ProviderName, *req.InstanceName, *req.ModelName, userID, req.Messages[0]["content"].(string), &apiConfig, &chatConfig, sender)

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 | 🏗️ Heavy lift

Streaming now drops the rest of the conversation.

Only req.Messages[0]["content"] is forwarded to ChatToModelStreamWithSender, so streaming requests ignore prior turns, assistant replies, and later user messages. The non-streaming path uses the full messages slice, so the two code paths now produce different answers for the same request.

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

In `@internal/handler/providers.go` around lines 879 - 880, The streaming call
currently forwards only req.Messages[0]["content"] to
h.modelProviderService.ChatToModelStreamWithSender which drops prior turns and
later messages; change the argument to pass the full conversation used by the
non-streaming path (e.g., the messages slice or the already-built `messages`
variable) so ChatToModelStreamWithSender receives the complete conversation
context rather than just the first message content.

Comment thread internal/service/model_service.go Resolved
Comment thread internal/service/model_service.go Resolved
@codecov

codecov Bot commented Apr 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (4ee0702) to head (c0afd50).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14523   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ 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 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: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/service/model_service.go (1)

765-771: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Guard NewInstance() before calling ChatWithMessages().

This branch assumes the driver can clone itself for a custom base URL, but the NewInstance() implementations shown in this PR return nil. That makes newProviderInfo.ChatWithMessages(...) a nil-pointer dereference for active local models.

Suggested fix
 		newURL := map[string]string{
 			region: extra["base_url"],
 		}
 		newProviderInfo := providerInfo.ModelDriver.NewInstance(newURL)
+		if newProviderInfo == nil {
+			return nil, common.CodeServerError, fmt.Errorf("provider %s does not support NewInstance", providerName)
+		}
 
 		var response *modelModule.ChatResponse
 		response, err = newProviderInfo.ChatWithMessages(modelName, apiConfig, messages, modelConfig)
🤖 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 765 - 771, The code calls
providerInfo.ModelDriver.NewInstance(...) and immediately invokes
newProviderInfo.ChatWithMessages(...), which can nil-deref because some
NewInstance implementations return nil; guard NewInstance by checking if
newProviderInfo == nil and, if nil, fall back to using providerInfo.ModelDriver
(or return an error) before calling ChatWithMessages; update the block around
NewInstance, newProviderInfo and ChatWithMessages in model_service.go to handle
the nil case (e.g., use original providerInfo.ModelDriver or return a clear
error) to avoid nil-pointer dereference.
internal/handler/providers.go (1)

829-880: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate the first streamed message before dereferencing it.

Line 880 assumes req.Messages is non-empty and that req.Messages[0]["content"] is a string. An empty payload or malformed first message will panic here instead of returning a 4xx.

Suggested fix
 	// Check if it's a stream request
 	if req.Stream {
+		if len(req.Messages) == 0 {
+			c.JSON(http.StatusBadRequest, gin.H{
+				"code":    400,
+				"message": "At least one message is required",
+			})
+			return
+		}
+
 		// Streaming with multimodal messages not yet supported
 		hasMultimodal := false
@@
 		if hasMultimodal {
 			c.JSON(http.StatusBadRequest, gin.H{
 				"code":    400,
 				"message": "Streaming with multimodal messages not yet supported",
 			})
 			return
 		}
+
+		firstContent, ok := req.Messages[0]["content"].(string)
+		if !ok || firstContent == "" {
+			c.JSON(http.StatusBadRequest, gin.H{
+				"code":    400,
+				"message": "Streaming requires the first message content to be a non-empty string",
+			})
+			return
+		}
@@
-		errorCode, err := h.modelProviderService.ChatToModelStreamWithSender(*req.ProviderName, *req.InstanceName, *req.ModelName, userID, req.Messages[0]["content"].(string), &apiConfig, &chatConfig, sender)
+		errorCode, err := h.modelProviderService.ChatToModelStreamWithSender(*req.ProviderName, *req.InstanceName, *req.ModelName, userID, firstContent, &apiConfig, &chatConfig, sender)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/handler/providers.go` around lines 829 - 880, The code dereferences
req.Messages[0]["content"] as a string before validating req.Messages exists and
the content type, which can panic; update the stream branch to first check
len(req.Messages) > 0, ensure req.Messages[0] has a "content" key, and assert
the value is a string (or return 400 if not) before calling
h.modelProviderService.ChatToModelStreamWithSender; adjust any early returns to
use the same error JSON shape and keep the sender and
ChatToModelStreamWithSender call unchanged aside from passing the
safely-extracted string.
♻️ Duplicate comments (2)
internal/entity/models/siliconflow.go (1)

115-135: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Forward thinking in the non-streaming request too.

This method reads reasoning_content below when chatModelConfig.Thinking is enabled, but the request body never asks SiliconFlow for a thinking-enabled response, so ReasonContent will usually stay empty here.

Suggested fix
 	if chatModelConfig != nil {
 		if chatModelConfig.Stream != nil {
 			reqBody["stream"] = *chatModelConfig.Stream
 		}
@@
 		if chatModelConfig.Stop != nil {
 			reqBody["stop"] = *chatModelConfig.Stop
 		}
+
+		if chatModelConfig.Thinking != nil {
+			if *chatModelConfig.Thinking {
+				reqBody["thinking"] = map[string]interface{}{
+					"type": "enabled",
+				}
+			} else {
+				reqBody["thinking"] = map[string]interface{}{
+					"type": "disabled",
+				}
+			}
+		}
 	}

Also applies to: 191-207

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

In `@internal/entity/models/siliconflow.go` around lines 115 - 135, The request
body never forwards chatModelConfig.Thinking, so SiliconFlow isn't asked to
return reasoning_content for non-stream calls; update the logic that builds
reqBody (the block that sets "stream", "max_tokens", "temperature", "top_p",
"stop") to also set a "thinking" (or the expected key used by SiliconFlow) entry
when chatModelConfig.Thinking != nil/true so ReasonContent is populated; apply
the same change in the other identical builder section referenced (around the
block that mirrors lines 191-207) to ensure both non-streaming and the other
request path include the thinking flag.
internal/entity/models/vllm.go (1)

205-207: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Guard the optional configs before dereferencing them.

This path still panics when callers omit apiConfig, apiConfig.ApiKey, or chatModelConfig, which is allowed by the new interface.

Suggested fix
 	region := "default"
-	if apiConfig.Region != nil {
+	if apiConfig != nil && apiConfig.Region != nil {
 		region = *apiConfig.Region
 	}
@@
-	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+	if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+		return nil, fmt.Errorf("api key is nil or empty")
+	}
+	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
@@
-	thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelClass, &content)
+	var modelClass *string
+	if chatModelConfig != nil {
+		modelClass = chatModelConfig.ModelClass
+	}
+	thinking, answer := GetThinkingAndAnswer(modelClass, &content)

Also applies to: 279-280, 323-323

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

In `@internal/entity/models/vllm.go` around lines 205 - 207, The code dereferences
apiConfig, apiConfig.ApiKey and chatModelConfig without nil checks which can
panic; update the vllm initialization to guard these optionals by checking if
apiConfig != nil before reading apiConfig.Region or apiConfig.ApiKey (use a
default region string and treat missing ApiKey as empty or return a clear error
as appropriate), and similarly check chatModelConfig != nil before accessing its
fields; apply the same nil-guard pattern to the other occurrences referenced
near the region and config usages (the blocks that set region and read
ApiKey/chatModelConfig) so all optional configs are safely handled.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/entity/models/deepseek.go`:
- Around line 113-145: The code is mutating the caller's chatModelConfig by
setting chatModelConfig.Thinking = nil inside the handling logic; instead
preserve input immutability by using a local flag variable (e.g., localThinking
or thinkingFlagState) to represent disabling/enabling thinking and do not assign
to chatModelConfig.Thinking; compute effort from chatModelConfig.Effort into a
local effort variable, set reasoning_effort and reqBody["thinking"] based on the
local variables (thinkingFlag and effort) and remove any assignments that write
back to chatModelConfig (specifically remove chatModelConfig.Thinking = nil).

In `@internal/entity/models/gitee.go`:
- Around line 79-87: The code is logging entire chat payloads
(apiMessages/messages) at info level which can leak sensitive data; locate the
logger.Info call that prints apiMessages (and the similar logger.Info at the
other location) and replace it with either a non-production debug-level log or a
redacted summary (e.g., only roles, message counts, or hashed/truncated content)
instead of full content; update the logger.Info(fmt.Sprintf("GiteeAPI messages:
%+v", apiMessages)) to something like logger.Debug or logger.Info with a safe
summary (roles/counts or masked content) so raw user prompts and multimodal URLs
are never written to standard logs.

In `@internal/entity/models/google.go`:
- Around line 67-111: The conversion currently coerces unknown/system roles to
genai.RoleUser and passes nil config to Models.GenerateContent, losing system
instructions and using a hard-coded "image/jpeg"; update the messages->contents
conversion in google.go to: preserve genai.RoleSystem for msg.Role == "system"
(do not default system to RoleUser), collect system message texts into a
GenerateContentConfig.SystemInstruction (or the appropriate field) and pass that
config into client.Models.GenerateContent(ctx, modelName, contents, config), and
for multimodal parts derive the MIME type from the image URL (e.g., inspect the
image_url map for a mime field or infer from the URL extension to support
image/png, image/jpeg, image/webp, image/heic, image/heif) instead of using the
hard-coded "image/jpeg". Ensure references: the message role mapping in the
conversion loop, building contents
(genai.NewContentFromText/NewContentFromParts), and the final
Models.GenerateContent call are updated accordingly.
- Around line 95-99: The code currently hardcodes "image/jpeg" when handling the
"image_url" case (see image_url key, itemMap and genai.NewPartFromURI), which
can cause MIME mismatches; change the handler to infer the MIME type from the
URL extension (map .png→image/png, .jpg/.jpeg→image/jpeg, .webp→image/webp,
.gif→image/gif, .heic/.heif→image/heic or image/heif), detect base64 data URLs
by parsing the "data:<mime>;base64,..." prefix to extract the MIME, and if
neither method yields a MIME, return an error instead of defaulting to JPEG;
then pass the derived MIME into genai.NewPartFromURI when appending to parts.

In `@internal/entity/models/vllm.go`:
- Around line 212-215: The current logic in vllm.go uses strings.Split into
modelType which fails for family names like "qwen3-0.6b"; update the routing
condition that selects z.URLSuffix.AsyncChat to use prefix matching on modelName
(e.g., strings.HasPrefix(modelName, "qwen") and similarly for "glm") instead of
exact equality on modelType so qwen-family models hit the async chat endpoint;
modify the conditional around modelName/modelType and ensure
z.URLSuffix.AsyncChat remains the target when the prefix matches.

In `@internal/entity/models/volcengine.go`:
- Around line 260-289: The code builds a thinking payload but doesn't record
whether the outgoing request actually enabled thinking, causing later parsing
(around the block that inspects reasoning_content) to assume thinking is
enabled; add a local boolean (e.g., thinkingEnabled) when you construct the
request in the chatModelConfig handling: set thinkingEnabled = false for effort
"none" or "minimal" (when thinkingFlag = "disabled") and true for other cases,
keep building reqBody["thinking"] and reqBody["reasoning_effort"] as before, and
then update the downstream parsing logic (the code that checks for
reasoning_content) to use this local thinkingEnabled flag instead of only
consulting chatModelConfig.Thinking so parsing only requires reasoning_content
when the request actually enabled thinking.

---

Outside diff comments:
In `@internal/handler/providers.go`:
- Around line 829-880: The code dereferences req.Messages[0]["content"] as a
string before validating req.Messages exists and the content type, which can
panic; update the stream branch to first check len(req.Messages) > 0, ensure
req.Messages[0] has a "content" key, and assert the value is a string (or return
400 if not) before calling h.modelProviderService.ChatToModelStreamWithSender;
adjust any early returns to use the same error JSON shape and keep the sender
and ChatToModelStreamWithSender call unchanged aside from passing the
safely-extracted string.

In `@internal/service/model_service.go`:
- Around line 765-771: The code calls providerInfo.ModelDriver.NewInstance(...)
and immediately invokes newProviderInfo.ChatWithMessages(...), which can
nil-deref because some NewInstance implementations return nil; guard NewInstance
by checking if newProviderInfo == nil and, if nil, fall back to using
providerInfo.ModelDriver (or return an error) before calling ChatWithMessages;
update the block around NewInstance, newProviderInfo and ChatWithMessages in
model_service.go to handle the nil case (e.g., use original
providerInfo.ModelDriver or return a clear error) to avoid nil-pointer
dereference.

---

Duplicate comments:
In `@internal/entity/models/siliconflow.go`:
- Around line 115-135: The request body never forwards chatModelConfig.Thinking,
so SiliconFlow isn't asked to return reasoning_content for non-stream calls;
update the logic that builds reqBody (the block that sets "stream",
"max_tokens", "temperature", "top_p", "stop") to also set a "thinking" (or the
expected key used by SiliconFlow) entry when chatModelConfig.Thinking !=
nil/true so ReasonContent is populated; apply the same change in the other
identical builder section referenced (around the block that mirrors lines
191-207) to ensure both non-streaming and the other request path include the
thinking flag.

In `@internal/entity/models/vllm.go`:
- Around line 205-207: The code dereferences apiConfig, apiConfig.ApiKey and
chatModelConfig without nil checks which can panic; update the vllm
initialization to guard these optionals by checking if apiConfig != nil before
reading apiConfig.Region or apiConfig.ApiKey (use a default region string and
treat missing ApiKey as empty or return a clear error as appropriate), and
similarly check chatModelConfig != nil before accessing its fields; apply the
same nil-guard pattern to the other occurrences referenced near the region and
config usages (the blocks that set region and read ApiKey/chatModelConfig) so
all optional configs are safely handled.
🪄 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: c16a1887-ebd0-481d-a1ad-ae834303c93d

📥 Commits

Reviewing files that changed from the base of the PR and between 88f137e and c0afd50.

📒 Files selected for processing (17)
  • internal/cli/http_client.go
  • internal/cli/user_command.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/gitee.go
  • internal/entity/models/google.go
  • internal/entity/models/minimax.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/entity/models/vllm.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/providers.go
  • internal/service/chat_session.go
  • internal/service/model_service.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/cli/user_command.go
  • internal/entity/models/dummy.go
  • internal/entity/models/moonshot.go
  • internal/service/chat_session.go

Comment on lines +113 to +145
if chatModelConfig.Thinking != nil {
if *chatModelConfig.Thinking {
var thinkingFlag string
effort := "high"
if chatModelConfig.Effort != nil {
effort = *chatModelConfig.Effort
}
switch effort {
case "none":
thinkingFlag = "disabled"
chatModelConfig.Thinking = nil
case "low":
thinkingFlag = "disabled"
chatModelConfig.Thinking = nil
case "medium":
thinkingFlag = "disabled"
chatModelConfig.Thinking = nil
case "high":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "high"
case "default":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "high"
case "max":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "max"
default:
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = effort
}
reqBody["thinking"] = map[string]interface{}{
"type": thinkingFlag,
}

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 | ⚡ Quick win

Don't mutate the caller's chatModelConfig.

Setting chatModelConfig.Thinking = nil here changes shared input state. A reused config will silently disable thinking on later calls, and shared use can race. Keep that as a local flag instead.

Suggested fix
+	thinkingEnabled := false
 	if chatModelConfig != nil {
@@
 		if chatModelConfig.Thinking != nil {
 			if *chatModelConfig.Thinking {
 				var thinkingFlag string
@@
 				switch effort {
 				case "none":
 					thinkingFlag = "disabled"
-					chatModelConfig.Thinking = nil
 				case "low":
 					thinkingFlag = "disabled"
-					chatModelConfig.Thinking = nil
 				case "medium":
 					thinkingFlag = "disabled"
-					chatModelConfig.Thinking = nil
 				case "high":
 					thinkingFlag = "enabled"
 					reqBody["reasoning_effort"] = "high"
+					thinkingEnabled = true
 				case "default":
 					thinkingFlag = "enabled"
 					reqBody["reasoning_effort"] = "high"
+					thinkingEnabled = true
 				case "max":
 					thinkingFlag = "enabled"
 					reqBody["reasoning_effort"] = "max"
+					thinkingEnabled = true
 				default:
 					thinkingFlag = "enabled"
 					reqBody["reasoning_effort"] = effort
+					thinkingEnabled = true
 				}
 				reqBody["thinking"] = map[string]interface{}{
 					"type": thinkingFlag,
 				}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/deepseek.go` around lines 113 - 145, The code is
mutating the caller's chatModelConfig by setting chatModelConfig.Thinking = nil
inside the handling logic; instead preserve input immutability by using a local
flag variable (e.g., localThinking or thinkingFlagState) to represent
disabling/enabling thinking and do not assign to chatModelConfig.Thinking;
compute effort from chatModelConfig.Effort into a local effort variable, set
reasoning_effort and reqBody["thinking"] based on the local variables
(thinkingFlag and effort) and remove any assignments that write back to
chatModelConfig (specifically remove chatModelConfig.Thinking = nil).

Comment on lines +79 to +87
// Convert messages to the format expected by API
apiMessages := make([]map[string]interface{}, len(messages))
for i, msg := range messages {
apiMessages[i] = map[string]interface{}{
"role": msg.Role,
"content": msg.Content,
}
}
logger.Info(fmt.Sprintf("GiteeAPI messages: %+v", apiMessages))

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 | ⚡ Quick win

Stop logging raw chat payloads at info level.

These logs now include full user prompts and multimodal content, which can leak PII, secrets, or private image URLs into application logs.

Also applies to: 136-136

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

In `@internal/entity/models/gitee.go` around lines 79 - 87, The code is logging
entire chat payloads (apiMessages/messages) at info level which can leak
sensitive data; locate the logger.Info call that prints apiMessages (and the
similar logger.Info at the other location) and replace it with either a
non-production debug-level log or a redacted summary (e.g., only roles, message
counts, or hashed/truncated content) instead of full content; update the
logger.Info(fmt.Sprintf("GiteeAPI messages: %+v", apiMessages)) to something
like logger.Debug or logger.Info with a safe summary (roles/counts or masked
content) so raw user prompts and multimodal URLs are never written to standard
logs.

Comment on lines +67 to +111
// Convert messages to Google SDK format
var contents []*genai.Content
for _, msg := range messages {
var role genai.Role
switch msg.Role {
case "user":
role = genai.RoleUser
case "model", "assistant":
role = genai.RoleModel
default:
role = genai.RoleUser
}

generateContentConfig := &genai.GenerateContentConfig{}
generateContentConfig.ThinkingConfig = &genai.ThinkingConfig{}
if chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
generateContentConfig.ThinkingConfig.IncludeThoughts = true
} else {
generateContentConfig.ThinkingConfig.IncludeThoughts = false
// Handle content based on type
switch c := msg.Content.(type) {
case string:
contents = append(contents, genai.NewContentFromText(c, role))
case []interface{}:
// Multimodal content - group parts within a single content
var parts []*genai.Part
for _, item := range c {
if itemMap, ok := item.(map[string]interface{}); ok {
contentType, _ := itemMap["type"].(string)
switch contentType {
case "text":
if text, ok := itemMap["text"].(string); ok {
parts = append(parts, genai.NewPartFromText(text))
}
case "image_url":
if imgMap, ok := itemMap["image_url"].(map[string]interface{}); ok {
if url, ok := imgMap["url"].(string); ok {
parts = append(parts, genai.NewPartFromURI(url, "image/jpeg"))
}
}
}
}
}
if len(parts) > 0 {
contents = append(contents, genai.NewContentFromParts(parts, role))
}
}
}

response, err := client.Models.GenerateContent(ctx, *modelName, contents, generateContentConfig)
// Generate content (non-streaming)
response, err := client.Models.GenerateContent(ctx, modelName, contents, 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 | 🟠 Major

🧩 Analysis chain

🌐 Web query:

Google Gemini SDK Go genai.GenerateContentConfig SystemInstruction

💡 Result:

In the Google Gemini SDK for Go (google.golang.org/genai), the genai.GenerateContentConfig struct has a field called SystemInstruction of type *genai.Content. This optional field sets developer-defined system instructions for the model, which guide its behavior throughout the conversation. It is text-only and can be a single content or multiple parts. Example usage: config := &genai.GenerateContentConfig{ SystemInstruction: genai.NewContentFromText("You are a cat. Your name is Neko.", "user"), } Or with Parts: config := &genai.GenerateContentConfig{ SystemInstruction: &genai.Content{ Parts: []*genai.Part{ {Text: "You're a language translator. Your mission is to translate text in English to French."}, }, }, } This is passed to client.Models.GenerateContent(ctx, model, contents, config). SystemInstruction persists across chat sessions when used with chats.create.

Citations:


🏁 Script executed:

# Check the current file and understand the imports
head -30 internal/entity/models/google.go

Repository: infiniflow/ragflow

Length of output: 928


🏁 Script executed:

# Search for any existing system instruction handling in the codebase
rg -i "systeminst" --type go

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Search for GenerateContentConfig usage patterns
rg "GenerateContentConfig" --type go -A 3 -B 3

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Get the full context of the file around lines 67-111
sed -n '49,120p' internal/entity/models/google.go | cat -n

Repository: infiniflow/ragflow

Length of output: 2585


🏁 Script executed:

# Check the current role handling and image URL processing
sed -n '67,111p' internal/entity/models/google.go | cat -n

Repository: infiniflow/ragflow

Length of output: 1696


🏁 Script executed:

# Search for any reference to image MIME types in the codebase
rg "image/jpeg|image_url" --type go -B 2 -A 2

Repository: infiniflow/ragflow

Length of output: 1989


🌐 Web query:

Google Gemini API supported image MIME types image_url

💡 Result:

Supported image MIME types for Gemini API image input (for image understanding / vision): - image/png - image/jpeg - image/webp - image/heic - image/heif How this applies to image_url / external URLs: - When passing an image via a URI/URL (rather than inline bytes), the API requires you to also provide the image’s media type (mimeType) alongside the fileUri/uri; the supported MIME types for images are the same set listed above. Notes: - Some other Gemini/Vertex AI docs list only the first three (PNG/JPEG/WEBP) as supported; the Gemini API “Image understanding” docs explicitly include HEIC and HEIF as well.

Citations:


Preserve system turns and pass system instructions via GenerateContentConfig.

Gemini's GenerateContent API requires system instructions to be passed separately via GenerateContentConfig.SystemInstruction rather than in the contents array. Currently, unknown roles (including "system") default to genai.RoleUser and the config is nil, so system messages lose their semantic meaning and higher priority. Pass system instructions in the config instead:

 	// Convert messages to Google SDK format
 	var contents []*genai.Content
+	var systemParts []*genai.Part
 	for _, msg := range messages {
 		var role genai.Role
 		switch msg.Role {
+		case "system":
+			switch c := msg.Content.(type) {
+			case string:
+				systemParts = append(systemParts, genai.NewPartFromText(c))
+			}
+			continue
 		case "user":
 			role = genai.RoleUser
 		case "model", "assistant":
 			role = genai.RoleModel
 		default:
 			role = genai.RoleUser
 		}
 		// ... rest of message handling
 
-	// Generate content (non-streaming)
-	response, err := client.Models.GenerateContent(ctx, modelName, contents, nil)
+	var config *genai.GenerateContentConfig
+	if len(systemParts) > 0 {
+		config = &genai.GenerateContentConfig{
+			SystemInstruction: genai.NewContentFromParts(systemParts, genai.RoleUser),
+		}
+	}
+
+	// Generate content (non-streaming)
+	response, err := client.Models.GenerateContent(ctx, modelName, contents, config)

Additionally, replace the hard-coded "image/jpeg" at line 50 with the actual MIME type detected from the image URL, since Gemini supports image/png, image/jpeg, image/webp, image/heic, and image/heif.

🤖 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 67 - 111, The conversion
currently coerces unknown/system roles to genai.RoleUser and passes nil config
to Models.GenerateContent, losing system instructions and using a hard-coded
"image/jpeg"; update the messages->contents conversion in google.go to: preserve
genai.RoleSystem for msg.Role == "system" (do not default system to RoleUser),
collect system message texts into a GenerateContentConfig.SystemInstruction (or
the appropriate field) and pass that config into
client.Models.GenerateContent(ctx, modelName, contents, config), and for
multimodal parts derive the MIME type from the image URL (e.g., inspect the
image_url map for a mime field or infer from the URL extension to support
image/png, image/jpeg, image/webp, image/heic, image/heif) instead of using the
hard-coded "image/jpeg". Ensure references: the message role mapping in the
conversion loop, building contents
(genai.NewContentFromText/NewContentFromParts), and the final
Models.GenerateContent call are updated accordingly.

Comment on lines +95 to +99
case "image_url":
if imgMap, ok := itemMap["image_url"].(map[string]interface{}); ok {
if url, ok := imgMap["url"].(string); ok {
parts = append(parts, genai.NewPartFromURI(url, "image/jpeg"))
}

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:

# First, let's examine the file and the specific lines mentioned
cat -n internal/entity/models/google.go | sed -n '85,110p'

Repository: infiniflow/ragflow

Length of output: 1029


🏁 Script executed:

# Get the full context around the image_url case to understand the input structure
cat -n internal/entity/models/google.go | sed -n '80,120p'

Repository: infiniflow/ragflow

Length of output: 1529


🏁 Script executed:

# Search for other occurrences of "image/jpeg" or similar MIME type hardcoding
rg "image/jpeg" internal/

Repository: infiniflow/ragflow

Length of output: 418


🏁 Script executed:

# Check if there's any mime_type handling elsewhere in the file
rg "mime_type" internal/

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Search for where this image_url structure is created or consumed
rg "image_url" internal/ --type go -B 3 -A 3

Repository: infiniflow/ragflow

Length of output: 1293


🏁 Script executed:

# Check if there are any tests that show the expected input format
fd "test" --type f internal/ | head -20

Repository: infiniflow/ragflow

Length of output: 369


🏁 Script executed:

# Look for OpenAI-related code to understand the input format better
rg -i "openai" internal/ --type go | head -20

Repository: infiniflow/ragflow

Length of output: 1886


🏁 Script executed:

# Check if there's documentation or examples for how multimodal content should be structured
rg -i "multimodal" . --type go -B 2 -A 2

Repository: infiniflow/ragflow

Length of output: 3855


🏁 Script executed:

# Check what OpenAI input format looks like - search for where image data is prepared
rg -i "detail.*low\|high\|auto" internal/ --type go

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Look for any MIME type detection or inference logic
rg "mime\|media.type\|content.type" internal/ --type go -i

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Check tests to see expected input format
find . -name "*test.go" -type f -exec grep -l "image_url" {} \;

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Review the types.go file to understand the expected Message structure better
cat -n internal/entity/models/types.go | head -50

Repository: infiniflow/ragflow

Length of output: 2531


🏁 Script executed:

# Check if there are any examples or comments about the expected image_url structure
rg "image_url" . --type go -B 5 -A 5 | grep -A 10 -B 10 "image_url"

Repository: infiniflow/ragflow

Length of output: 1723


🏁 Script executed:

# Look for how this Message structure is populated - check if there's a conversion layer
rg -i "url.*jpeg\|image.*format\|mime" internal/ --type go -B 2 -A 2

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Check if there's an OpenAI integration that shows the expected format
find . -name "*openai*" -o -name "*OpenAI*" | head -10

Repository: infiniflow/ragflow

Length of output: 281


🏁 Script executed:

# Check the datasets.go file to understand how MIME types are validated
cat -n internal/service/datasets.go | grep -B 10 -A 10 "image/jpeg"

Repository: infiniflow/ragflow

Length of output: 1661


🏁 Script executed:

# Check if there's any URL parsing or file type inference from URLs
rg "filepath\|path\.Ext\|url\.Path\|file.*ext" internal/ --type go | head -20

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Look at the utility/file.go to see if there's MIME type detection logic we can reuse
cat -n internal/utility/file.go | grep -B 5 -A 5 "image/jpeg"

Repository: infiniflow/ragflow

Length of output: 430


🏁 Script executed:

# Check if OpenAI API format actually includes a way to specify MIME type
rg -i "detail\|image_url" . --type py -A 3 -B 3 | head -40

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Check if there's any URL file extension parsing logic elsewhere
rg "url.*ext\|filepath\|path\.ext" internal/ --type go -i -B 2 -A 2

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Look at how the image_url is created - check OpenAI API implementation for reference
cat -n ./api/apps/restful_apis/openai_api.py | grep -B 10 -A 10 "image_url"

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Check the full google.go file to understand the context better
wc -l internal/entity/models/google.go

Repository: infiniflow/ragflow

Length of output: 99


🏁 Script executed:

# Get the function signature and full context
cat -n internal/entity/models/google.go | sed -n '1,110p'

Repository: infiniflow/ragflow

Length of output: 3859


🏁 Script executed:

# Check the OpenAI API Python implementation to see the expected format
cat -n ./api/apps/restful_apis/openai_api.py | head -100

Repository: infiniflow/ragflow

Length of output: 4157


🏁 Script executed:

# Search for how images are handled in the Python API
rg "image" ./api/apps/restful_apis/openai_api.py -B 3 -A 3

Repository: infiniflow/ragflow

Length of output: 313


🏁 Script executed:

# Look at the test files to understand the expected format
cat -n ./test/testcases/test_http_api/test_session_management/test_chat_completions_openai.py | head -150

Repository: infiniflow/ragflow

Length of output: 7797


🏁 Script executed:

# Check if there's any documentation or examples of the multimodal content format
rg "type.*image_url\|image_url.*type" . -B 5 -A 5 --type py --type go | head -50

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Look for any conversion or transformation of messages before they reach the google.go handler
rg "ChatWithMessages" internal/ --type go -B 5 -A 10 | head -100

Repository: infiniflow/ragflow

Length of output: 6595


🏁 Script executed:

# Check if the image URL contains file extension information we can use to infer MIME type
rg "\.png\|\.jpg\|\.jpeg\|\.webp\|\.gif" . --type go -B 2 -A 2 | head -30

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Look at the Gemini API documentation or examples in the codebase
rg "genai\." internal/entity/models/google.go -B 2 -A 2

Repository: infiniflow/ragflow

Length of output: 2231


🌐 Web query:

Gemini API genai.NewPartFromURI MIME type requirements documentation

💡 Result:

The genai.NewPartFromURI function in the Google Gen AI Go SDK (google.golang.org/genai) creates a *genai.Part from a file URI and MIME type string. It is used to reference uploaded files (via Files API) or Cloud Storage URIs for multimodal inputs in Gemini API requests. Signature: func NewPartFromURI(fileURI, mimeType string) *Part Usage example from official docs: parts := []*genai.Part{ genai.NewPartFromText("Describe this audio clip"), genai.NewPartFromURI(file.URI, file.MIMEType), } contents := []*genai.Content{ genai.NewContentFromParts(parts, genai.RoleUser), } response, err := client.Models.GenerateContent(ctx, "gemini-2.0-flash", contents, nil) MIME type is a required string parameter (e.g., "image/jpeg", "audio/mpeg", "application/pdf"). It must match a Gemini-supported type for the file content, or the API will reject unsupported MIME types (e.g., DOCX fails with 400 error). Supported MIME types (from Gemini multimodal docs): - Images: image/png, image/jpeg, image/webp - Video: video/mp4, video/mpeg, video/mov, etc. - Audio: audio/mpeg, audio/mp3, audio/wav, etc. - Documents: application/pdf, text/plain Full lists and limits in official Files API and input requirements docs. MIME type is validated server-side; use the MIME type from the uploaded file metadata (file.MIMEType).

Citations:


🌐 Web query:

OpenAI vision API image_url format mime_type field specification

💡 Result:

OpenAI vision API: there is no supported mime_type field in the image_url object. What OpenAI specifies instead (for vision inputs): 1) Use image_url.url inside the message content part. - For HTTP images: image_url: { url: "https://..." } - For base64 images: image_url: "data:;base64," where the data-URL includes the mime type (example shown with image/jpeg). 2) The only additional field shown in the image_url object is detail (optional). - image_url: { url: "...", detail: "low"|"high"|"auto" } Example (base64 data URL with a MIME type in the data URL): { "type": "input_image", "image_url": "data:image/jpeg;base64,<BASE64_IMAGE>" } So, if your request is something like: image_url: { url: "...", mime_type: "image/jpeg" } that mime_type field is not part of the documented schema and should be omitted; the MIME type should be encoded in the data URL when you use base64. Note: Supported image formats are documented as JPEG, PNG, and WEBP (and non-animated GIF) for image inputs.

Citations:


🏁 Script executed:

# Check if there's any prior art in the codebase for MIME type inference from URLs
rg "filepath\|path\.Ext\|Ext\(" internal/ --type go -B 2 -A 2 | head -40

Repository: infiniflow/ragflow

Length of output: 44


Hardcoding "image/jpeg" will cause multimodal requests with non-JPEG images to fail.

genai.NewPartFromURI requires an accurate MIME type that matches the actual image format. The Gemini API validates and rejects mismatched MIME types, so labeling PNG/WEBP/GIF/HEIC images as JPEG will cause 400 errors.

However, the OpenAI-compatible input format does not include a mime_type field—only url and an optional detail field. Instead, infer the MIME type from:

  1. The file extension in the URL (.png → image/png, .jpg/.jpeg → image/jpeg, .webp → image/webp)
  2. For base64 data URLs, extract it from the data:<mime-type>;base64,... scheme
  3. If detection fails, return an error rather than defaulting to JPEG
🤖 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 95 - 99, The code currently
hardcodes "image/jpeg" when handling the "image_url" case (see image_url key,
itemMap and genai.NewPartFromURI), which can cause MIME mismatches; change the
handler to infer the MIME type from the URL extension (map .png→image/png,
.jpg/.jpeg→image/jpeg, .webp→image/webp, .gif→image/gif, .heic/.heif→image/heic
or image/heif), detect base64 data URLs by parsing the "data:<mime>;base64,..."
prefix to extract the MIME, and if neither method yields a MIME, return an error
instead of defaulting to JPEG; then pass the derived MIME into
genai.NewPartFromURI when appending to parts.

Comment on lines +212 to +215
// For qwen/glm models, use async chat endpoint
modelType := strings.Split(modelName, "-")[0]
if modelType == "qwen" || modelType == "glm" {
url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat)

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 | ⚡ Quick win

Use prefix matching for qwen-family async routing.

Line 213 splits on -, so qwen3-0.6b becomes qwen3 and never matches the exact "qwen" check. Those models will still hit the sync endpoint.

Suggested fix
 	modelType := strings.Split(modelName, "-")[0]
-	if modelType == "qwen" || modelType == "glm" {
+	if strings.HasPrefix(modelType, "qwen") || modelType == "glm" {
 		url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat)
 	}
📝 Committable suggestion

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

Suggested change
// For qwen/glm models, use async chat endpoint
modelType := strings.Split(modelName, "-")[0]
if modelType == "qwen" || modelType == "glm" {
url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat)
// For qwen/glm models, use async chat endpoint
modelType := strings.Split(modelName, "-")[0]
if strings.HasPrefix(modelType, "qwen") || modelType == "glm" {
url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat)
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/vllm.go` around lines 212 - 215, The current logic in
vllm.go uses strings.Split into modelType which fails for family names like
"qwen3-0.6b"; update the routing condition that selects z.URLSuffix.AsyncChat to
use prefix matching on modelName (e.g., strings.HasPrefix(modelName, "qwen") and
similarly for "glm") instead of exact equality on modelType so qwen-family
models hit the async chat endpoint; modify the conditional around
modelName/modelType and ensure z.URLSuffix.AsyncChat remains the target when the
prefix matches.

Comment on lines +260 to +289
if chatModelConfig.Thinking != nil {
if *chatModelConfig.Thinking {
var thinkingFlag string
effort := "medium"
if chatModelConfig.Effort != nil {
effort = *chatModelConfig.Effort
}
switch effort {
case "none", "minimal":
thinkingFlag = "disabled"
reqBody["reasoning_effort"] = "minimal"
case "low":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "low"
case "medium":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
case "auto", "default":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
case "high":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "high"
default:
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = effort
}
reqBody["thinking"] = map[string]interface{}{
"type": thinkingFlag,
}

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 | ⚡ Quick win

Keep response parsing aligned with the effective thinking mode.

If Effort is "none" or "minimal", this request sends thinking.type = disabled, but Lines 355-359 still treat the call as thinking-enabled and error when reasoning_content is missing. Track a local thinkingEnabled flag from the request you actually send.

Suggested fix
+	thinkingEnabled := false
 	if chatModelConfig != nil {
@@
 		if chatModelConfig.Thinking != nil {
 			if *chatModelConfig.Thinking {
 				var thinkingFlag string
@@
 				switch effort {
 				case "none", "minimal":
 					thinkingFlag = "disabled"
 					reqBody["reasoning_effort"] = "minimal"
 				case "low":
 					thinkingFlag = "enabled"
 					reqBody["reasoning_effort"] = "low"
@@
 				}
+				thinkingEnabled = thinkingFlag == "enabled"
 				reqBody["thinking"] = map[string]interface{}{
 					"type": thinkingFlag,
 				}
@@
-	if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
+	if thinkingEnabled {
 		reasonContent, ok = messageMap["reasoning_content"].(string)
 		if !ok {
 			return nil, fmt.Errorf("invalid reasonContent format")

Also applies to: 355-359

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

In `@internal/entity/models/volcengine.go` around lines 260 - 289, The code builds
a thinking payload but doesn't record whether the outgoing request actually
enabled thinking, causing later parsing (around the block that inspects
reasoning_content) to assume thinking is enabled; add a local boolean (e.g.,
thinkingEnabled) when you construct the request in the chatModelConfig handling:
set thinkingEnabled = false for effort "none" or "minimal" (when thinkingFlag =
"disabled") and true for other cases, keep building reqBody["thinking"] and
reqBody["reasoning_effort"] as before, and then update the downstream parsing
logic (the code that checks for reasoning_content) to use this local
thinkingEnabled flag instead of only consulting chatModelConfig.Thinking so
parsing only requires reasoning_content when the request actually enabled
thinking.

@JinHai-CN
JinHai-CN merged commit 265f92c into infiniflow:main Apr 30, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 30, 2026
1 task done
@coderabbitai coderabbitai Bot mentioned this pull request Jul 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants