Skip to content

fix: Gemini & Vertex empty content error - #1260

Merged
Calcium-Ion merged 1 commit into
QuantumNous:alphafrom
tbphp:fix-gemini-empty-content-error
Jun 19, 2025
Merged

fix: Gemini & Vertex empty content error#1260
Calcium-Ion merged 1 commit into
QuantumNous:alphafrom
tbphp:fix-gemini-empty-content-error

Conversation

@tbphp

@tbphp tbphp commented Jun 19, 2025

Copy link
Copy Markdown
Contributor

PR 报告:修复 Gemini/Vertex 因消息内容为空导致的请求失败问题

一、问题描述

问题现象:
当 API 请求中 messages 数组包含 content 字段为空的条目时,向 Gemini 及 Vertex 渠道发送的请求会失败,上游服务返回 400 Bad Request 错误。

复现步骤:

curl -X POST http://127.0.0.1:3000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-123456" \
-d '{
    "model": "gemini-pro",
    "messages": [
        {
            "role": "user",
            "content": "hello"
        },
        {
            "role": "user",
            "content": "" 
        }
    ]
}'

上游错误响应 (Error Response):

{
    "error": {
        "message": "Unable to submit request because it must include at least one parts field...",
        "code": 400
    }
}

背景:
此问题在多个客户端(如 SillyTavern, Cherry Studio 等)中都有出现,推测可能与上游服务(Google)近期对 API 请求参数校验规则的调整有关(因为最近才收到比较多的反馈)。


二、根本原因分析

在请求转换过程中,项目将 OpenAI 格式的 messages 转换为 Gemini 格式。当遇到 content 为空的 message 时,会生成一个 parts 字段为 nullcontent 对象。

转换后错误的请求体片段:

{
  "contents": [
    {
      "role": "user",
      "parts": [{ "text": "hello" }]
    },
    {
      "role": "user",
      "parts": null  // 此处为问题根源
    }
  ]
}

根据 Gemini API 的规范,parts 字段必须是一个包含至少一个有效元素的数组,null 值或空数组均不被接受,从而导致请求校验失败。


三、解决方案

在将消息转换为 Gemini 格式的 contents 数组时,增加一道过滤逻辑:如果一个 message 对象转换后的 parts 数组为空,则直接跳过该消息,不将其添加到最终的 contents 数组中。

代码实现:
relay/channel/gemini/relay-gemini.go 文件约 377 行处,增加对 parts 数组长度的判断。

// 代码示例
if len(content.Parts) > 0 {
    // 只有当 parts 不为空时,才将此 content 添加到请求体中
    geminiRequest.Contents = append(geminiRequest.Contents, content)
}

此修改可以从根本上避免生成不符合上游规范的请求体。


四、测试与验证

已在本地环境完成以下场景的回归测试,确保修复方案的正确性,且未引入新的问题:

  • 核心功能:成功处理包含空消息的请求,不再报错。
  • 多模态:图片和文本混合输入功能正常。
  • 纯图片:只有图片没有文字的场景,上游报错400。经验证不是此pr影响,目前正式版本仍然有此问题。
  • 多渠道兼容性
    • ✅ Google AI Studio
    • ✅ Vertex AI
    • ✅ Vertex Express Mode(快速模式)
  • 功能完整性
    • ✅ 流式与非流式输出
    • ✅ 长上下文(>200k)处理
    • ✅ 长时间(>5m)请求
  • MCP:支持正常。

除了本地自测之外,也正在邀请我站内的用户进行更大范围的用户场景测试,也许1,2天后会更新多场景测试结果。此修复对于提升 Gemini 渠道的稳定性至关重要,建议合并。

Summary by CodeRabbit

  • Bug Fixes
    • Improved message handling to prevent empty messages from appearing in requests.

@coderabbitai

coderabbitai Bot commented Jun 19, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The update changes the logic in the CovertGemini2OpenAI function to only append GeminiChatContent objects to the request if their Parts slice is not empty, thereby filtering out empty message entries from the payload.

Changes

File(s) Change Summary
relay/channel/gemini/relay-gemini.go Modified logic to append GeminiChatContent only if its Parts slice is non-empty in CovertGemini2OpenAI.

Poem

In Gemini’s relay, the code now checks twice,
No empty messages—just content precise.
Only with parts does a message get through,
Filtering the empty, letting meaning accrue.
A hop and a skip, the payload’s now neat—
The relay’s more clever, and messages sweet!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0b9b21e and a87d427.

📒 Files selected for processing (1)
  • relay/channel/gemini/relay-gemini.go (1 hunks)
🔇 Additional comments (1)
relay/channel/gemini/relay-gemini.go (1)

377-379: Excellent fix for the empty content issue!

This conditional check effectively prevents the root cause of the 400 Bad Request errors by filtering out messages with empty Parts arrays before they're sent to the Gemini API. The solution is minimal, targeted, and maintains backward compatibility while addressing the specific issue described in the PR objectives.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Calcium-Ion
Calcium-Ion changed the base branch from main to alpha June 19, 2025 06:34
@Calcium-Ion
Calcium-Ion merged commit ab78efc into QuantumNous:alpha Jun 19, 2025
@QingyeSC

Copy link
Copy Markdown
Contributor

感谢大佬的帮助,也遇到类似问题

@tbphp

tbphp commented Jun 20, 2025

Copy link
Copy Markdown
Contributor Author

经过一天更广的用于多场景测试,确定parts相关问题已经修复,且多个复杂场景都使用正常。

@tbphp
tbphp deleted the fix-gemini-empty-content-error branch September 29, 2025 12:15
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
…nt-error

fix: Gemini & Vertex empty content error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants