Skip to content

fix(go): send Gemini system prompts via system_instruction instead of user turn - #17449

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
abhayishere:fix/gemini-go-system-instruction
Jul 31, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
abhayishere:fix/gemini-go-system-instruction

Conversation

@abhayishere

Copy link
Copy Markdown
Contributor

Summary

  • Fixes [Go] Gemini: system prompt is sent as a user message instead of system_instruction #17330: the Go Gemini driver (internal/entity/models/google.go) was dropping
    role: "system" messages into the conversation as a plain user turn, since the role
    switch in googleChatContents had no system case and fell through to
    genai.RoleUser. GenerateContent/GenerateContentStream were also always called
    with either a nil config or one that never set SystemInstruction, so there was no
    path to send a real system instruction even if one had been extracted.
  • Add googleSystemInstruction(messages) to collect all role: "system" message parts
    into a single *genai.Content, and exclude those messages from googleChatContents.
  • Thread the extracted system instruction through googleGenerateContentConfig, which
    now sets GenerateContentConfig.SystemInstruction and only returns nil when there is
    truly nothing to configure (previously it bailed out early whenever chatModelConfig
    was nil, which is the common case for calls that only carry a system + user message).
  • Wire this into both ChatWithMessages and ChatStreamlyWithSender.
  • This brings the Go driver in line with the Python GoogleChat driver
    (rag/llm/chat_model.py:1374), which already sets system_instruction correctly.

Test plan

  • internal/entity/models/google_test.go: added
    TestGoogleSystemInstructionExtractedFromMessages (system message excluded from
    contents, routed into SystemInstruction) and
    TestGoogleSystemInstructionNilWhenNoSystemMessage (no system message → nil
    instruction, nil config when nothing else is set).
  • Updated the existing TestGoogleGenerateContentConfigConvertsTools call site for
    the new googleGenerateContentConfig signature.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jul 27, 2026
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Gemini system messages are extracted into SystemInstruction, removed from chat contents, validated for text-only content, and passed through request configuration for regular and streaming Google model calls. Tests cover extraction, rejection, configuration, overflow handling, and conversational-message validation.

Changes

Gemini system instruction routing

Layer / File(s) Summary
System message translation and request configuration
internal/entity/models/google.go, internal/entity/models/google_test.go
System messages are converted into Gemini instruction parts and excluded from chat contents; configuration preserves the instruction, validates token bounds, returns nil when unused, and rejects image content.
Streaming and non-streaming request integration
internal/entity/models/google.go, internal/entity/models/google_test.go
ChatWithMessages and ChatStreamlyWithSender reject system-only inputs and pass extracted instructions into Gemini generation configuration.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested labels: 🐞 bug

Poem

A rabbit hops through prompts so bright,
System words now take their proper flight.
User turns stay in their lane,
Streams and chats share the same refrain.
Gemini reads the roles just right!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes satisfy #17330 by moving system messages into Gemini system_instruction and excluding them from chat contents.
Out of Scope Changes check ✅ Passed No unrelated code changes are evident; the extra validation and tests support the same Gemini fix.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly captures the main change: routing Gemini system prompts through system_instruction instead of a user turn.
Description check ✅ Passed The description matches the required Summary template and adds useful context plus testing details.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b793ee and 06304d2.

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

Comment thread internal/entity/models/google.go Outdated
Comment on lines +123 to +129
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)...)

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.

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

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

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


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.

Comment thread internal/entity/models/google.go Resolved
@abhayishere
abhayishere force-pushed the fix/gemini-go-system-instruction branch from 06304d2 to c6e414a Compare July 27, 2026 17:15

@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

🧹 Nitpick comments (1)
internal/entity/models/google_test.go (1)

268-295: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add 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 GenerateContent and GenerateContentStream with SystemInstruction populated; 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

📥 Commits

Reviewing files that changed from the base of the PR and between 06304d2 and c6e414a.

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

Comment thread internal/entity/models/google.go Resolved
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jul 28, 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.

🧹 Nitpick comments (1)
internal/entity/models/google_test.go (1)

520-552: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover multiple system messages in the extraction test.

This test uses only one system message, 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 from contents. 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

📥 Commits

Reviewing files that changed from the base of the PR and between c6e414a and cfbab77.

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

@JinHai-CN
JinHai-CN requested a review from Haruko386 July 28, 2026 11:21
@Haruko386
Haruko386 marked this pull request as draft July 29, 2026 09:19
@Haruko386
Haruko386 marked this pull request as ready for review July 29, 2026 09:19
@Haruko386 Haruko386 added the ci Continue Integration label Jul 29, 2026
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Jul 29, 2026
@Haruko386 Haruko386 removed the 🐞 bug Something isn't working, pull request that fix bug. label Jul 29, 2026
@Haruko386
Haruko386 marked this pull request as draft July 29, 2026 09:26
@Haruko386
Haruko386 marked this pull request as ready for review July 29, 2026 09:26
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Jul 29, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed ci Continue Integration labels Jul 29, 2026

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jul 31, 2026
@Haruko386
Haruko386 marked this pull request as draft July 31, 2026 07:51
@Haruko386 Haruko386 removed 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration labels Jul 31, 2026
@Haruko386
Haruko386 marked this pull request as ready for review July 31, 2026 07:51
@Haruko386 Haruko386 added the ci Continue Integration label Jul 31, 2026
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Jul 31, 2026
@Haruko386 Haruko386 removed ci Continue Integration 🐞 bug Something isn't working, pull request that fix bug. labels Jul 31, 2026
@Haruko386
Haruko386 marked this pull request as draft July 31, 2026 07:52
@Haruko386
Haruko386 marked this pull request as ready for review July 31, 2026 07:52
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Jul 31, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed 🐞 bug Something isn't working, pull request that fix bug. labels Jul 31, 2026
@Haruko386
Haruko386 marked this pull request as draft July 31, 2026 07:54
@Haruko386
Haruko386 marked this pull request as ready for review July 31, 2026 07:54
@Haruko386 Haruko386 removed the ci Continue Integration label Jul 31, 2026
@Haruko386
Haruko386 marked this pull request as draft July 31, 2026 07:55
@Haruko386
Haruko386 marked this pull request as ready for review July 31, 2026 07:55
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Jul 31, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed 🐞 bug Something isn't working, pull request that fix bug. labels Jul 31, 2026
@JinHai-CN
JinHai-CN merged commit c8fbd97 into infiniflow:main Jul 31, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Go] Gemini: system prompt is sent as a user message instead of system_instruction

4 participants