Repository navigation
fix(go): send Gemini system prompts via system_instruction instead of user turn - #17449
Conversation
📝 WalkthroughWalkthroughGemini system messages are extracted into ChangesGemini system instruction routing
Estimated code review effort: 3 (Moderate) | ~20 minutes Suggested labels: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/google.go`:
- Around line 123-129: Update googleSystemInstruction to validate each system
message’s content before calling googleMessageParts, returning a local
validation error when any non-text block, including image_url content, is
present. Preserve conversion for text-only system messages and add a regression
test covering rejection of image-bearing system content.
- Around line 388-392: Validate that googleChatContents returns at least one
non-system message before making either Gemini request. In
internal/entity/models/google.go lines 388-392, return a local error before
GenerateContent when contents is empty; apply the same validation before
GenerateContentStream at lines 428-432, preserving the existing
systemInstruction handling.
🪄 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 Plus
Run ID: d2241075-24e6-44af-8734-71ec6f4016fd
📒 Files selected for processing (2)
internal/entity/models/google.gointernal/entity/models/google_test.go
| func googleSystemInstruction(messages []Message) *genai.Content { | ||
| var parts []*genai.Part | ||
| for _, msg := range messages { | ||
| if msg.Role != "system" { | ||
| continue | ||
| } | ||
| parts = append(parts, googleMessageParts(msg.Content)...) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate file =="
git ls-files | rg '(^|/)google\.go$|internal/entity/models|gemini|genai' || true
echo "== relevant file outline =="
ast-grep outline internal/entity/models/google.go --view expanded 2>/dev/null || true
echo "== google.go relevant section =="
sed -n '1,180p' internal/entity/models/google.go
echo "== usages of googleMessageParts and googleSystemInstruction =="
rg -n "googleMessageParts|googleSystemInstruction|googleGenerateContentConfig|ChatWithMessages|ChatStreamlyWithSender" internal/entity/models google -S || true
echo "== git diff stat/name =="
git diff --stat || true
git diff -- internal/entity/models/google.go | sed -n '1,240p' || true
echo "== package imports/constants nearby =="
sed -n '1,80p' internal/entity/models/google.goRepository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== google.go googleMessageParts and call sites =="
sed -n '123,260p' internal/entity/models/google.go
sed -n '360,445p' internal/entity/models/google.go
echo "== common message types for role/content fields =="
rg -n "type Message|Content interface|image_url|image" internal/entity/models/types.go internal/entity/models/common.go internal/entity/models -g '*.go' -S | head -n 160
echo "== google tests mentioning system/image =="
rg -n "system|image|Google|gemini|GenerateContent|StreamGenerateContent" internal/entity/models/google_test.go internal/entity/models -S -g '*google*.go' -g '*common*.go' | head -n 240
echo "== go.sum google genai version =="
rg -n 'google.golang.org/genai|ai.google.dev/gemini|SystemInstruction' go.sum -S || trueRepository: infiniflow/ragflow
Length of output: 32700
🌐 Web query:
Google Gemini Generate Content API SystemInstruction text only image content
💡 Result:
The Google Gemini Generate Content API system instruction parameter is explicitly designed for text-only input [1][2][3]. While the API itself is multimodal and supports images, audio, video, and PDF files within the main contents of a request [1][4][5], system instructions are currently limited to text [1][3]. Official documentation consistently specifies that the systemInstruction field expects an object containing text-based content [1][6][2]. Attempts to include non-text data, such as images, in the system instruction field can lead to errors [7]. If you need to provide multimodal context to guide the model's behavior, you should include those assets within the main contents array of your request rather than the system instruction parameter [4][5].
Citations:
- 1: https://ai.google.dev/api/generate-content
- 2: https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1beta1/projects.locations.endpoints/generateContent
- 3: https://github.com/google-gemini/deprecated-generative-ai-python/blob/main/docs/api/google/generativeai/protos/GenerateContentRequest.md
- 4: https://ai.google.dev/gemini-api/docs/image-understanding
- 5: https://ai.google.dev/gemini-api/docs/generate-content/image-understanding
- 6: https://ai.google.dev/gemini-api/docs/generate-content/text-generation
- 7: responseModalities with image not support system instruction? Why not just skip instead of error? googleapis/js-genai#345
Reject non-text system-message content.
googleSystemInstruction passes system-role content through googleMessageParts, which converts image_url blocks into URI parts. Gemini’s systemInstruction field is text-only, so image-bearing system messages can produce unsupported requests. Return a local validation error when a system message contains non-text content and add a regression test for that path.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/google.go` around lines 123 - 129, Update
googleSystemInstruction to validate each system message’s content before calling
googleMessageParts, returning a local validation error when any non-text block,
including image_url content, is present. Preserve conversion for text-only
system messages and add a regression test covering rejection of image-bearing
system content.
06304d2 to
c6e414a
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/entity/models/google_test.go (1)
268-295: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd mixed-message request-path coverage.
This test only exercises the early system-only rejection branch. It does not prove that mixed system/user input reaches both
GenerateContentandGenerateContentStreamwithSystemInstructionpopulated; a wiring regression in either path would still pass. Add captured-request assertions for both paths, ideally including multiple system messages and a multimodal user message.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/google_test.go` around lines 268 - 295, Extend TestGoogleModelChatRequiresConversationalMessage or add a focused companion test covering mixed system/user messages through both ChatWithMessages and ChatStreamlyWithSender. Capture the requests sent to GenerateContent and GenerateContentStream, using multiple system messages and a multimodal user message, then assert each request populates SystemInstruction correctly and preserves the user content; retain the existing system-only rejection assertions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/google.go`:
- Around line 265-266: Validate ChatConfig.MaxTokens before assigning it to
cfg.MaxOutputTokens in the chat model configuration path, ensuring non-nil
values do not exceed math.MaxInt32 before narrowing from int to int32. Preserve
the existing assignment for values within the supported range and apply the
repository’s established invalid-configuration handling for out-of-range values.
---
Nitpick comments:
In `@internal/entity/models/google_test.go`:
- Around line 268-295: Extend TestGoogleModelChatRequiresConversationalMessage
or add a focused companion test covering mixed system/user messages through both
ChatWithMessages and ChatStreamlyWithSender. Capture the requests sent to
GenerateContent and GenerateContentStream, using multiple system messages and a
multimodal user message, then assert each request populates SystemInstruction
correctly and preserves the user content; retain the existing system-only
rejection assertions.
🪄 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 Plus
Run ID: d758aab3-c5ac-4798-91b8-ab9461b9f56b
📒 Files selected for processing (2)
internal/entity/models/google.gointernal/entity/models/google_test.go
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/google_test.go (1)
520-552: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCover multiple system messages in the extraction test.
This test uses only one
systemmessage, so it would still pass if the implementation accidentally retained only the first one. Add a second system message and assert that both text parts are preserved while both messages remain excluded fromcontents. This protects the PR objective for system messages in the plural.Suggested test adjustment
{Role: "system", Content: "You are a helpful assistant."}, + {Role: "system", Content: "Be concise."}, {Role: "user", Content: "Hello"}, @@ - if systemInstruction == nil || len(systemInstruction.Parts) != 1 { - t.Fatalf("systemInstruction = %#v, want one part", systemInstruction) + if systemInstruction == nil || len(systemInstruction.Parts) != 2 { + t.Fatalf("systemInstruction = %#v, want two parts", systemInstruction) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/google_test.go` around lines 520 - 552, Add a second system message to TestGoogleSystemInstructionExtractedFromMessages, verify googleChatContents excludes both system messages while retaining the user content, and assert googleSystemInstruction contains both text parts in order with the expected values.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/entity/models/google_test.go`:
- Around line 520-552: Add a second system message to
TestGoogleSystemInstructionExtractedFromMessages, verify googleChatContents
excludes both system messages while retaining the user content, and assert
googleSystemInstruction contains both text parts in order with the expected
values.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 8d6e327b-d4b5-4122-8eb0-65754975b9c2
📒 Files selected for processing (2)
internal/entity/models/google.gointernal/entity/models/google_test.go
Summary
internal/entity/models/google.go) was droppingrole: "system"messages into the conversation as a plainuserturn, since the roleswitch in
googleChatContentshad nosystemcase and fell through togenai.RoleUser.GenerateContent/GenerateContentStreamwere also always calledwith either a
nilconfig or one that never setSystemInstruction, so there was nopath to send a real system instruction even if one had been extracted.
googleSystemInstruction(messages)to collect allrole: "system"message partsinto a single
*genai.Content, and exclude those messages fromgoogleChatContents.googleGenerateContentConfig, whichnow sets
GenerateContentConfig.SystemInstructionand only returnsnilwhen there istruly nothing to configure (previously it bailed out early whenever
chatModelConfigwas
nil, which is the common case for calls that only carry a system + user message).ChatWithMessagesandChatStreamlyWithSender.GoogleChatdriver(
rag/llm/chat_model.py:1374), which already setssystem_instructioncorrectly.Test plan
internal/entity/models/google_test.go: addedTestGoogleSystemInstructionExtractedFromMessages(system message excluded fromcontents, routed intoSystemInstruction) andTestGoogleSystemInstructionNilWhenNoSystemMessage(no system message → nilinstruction, nil config when nothing else is set).
TestGoogleGenerateContentConfigConvertsToolscall site forthe new
googleGenerateContentConfigsignature.