Skip to content

OAI生图接口支持gemini 3 pro image preview - #2305

Merged
creamlike1024 merged 2 commits into
QuantumNous:mainfrom
feitianbubu:pr/add-gemini-3-pro-image-preview-oai
Nov 26, 2025
Merged

creamlike1024 merged 2 commits into
QuantumNous:mainfrom
feitianbubu:pr/add-gemini-3-pro-image-preview-oai

Conversation

@feitianbubu

@feitianbubu feitianbubu commented Nov 26, 2025 •

Copy link
Copy Markdown
Member

之前的gemini 3 pro image preview只支持在chat中生图, 现在增加在oai的标准生图接口的支持
请求格式:

curl http://localhost:3000/v1/images/generations \
  --request POST \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "gemini-3-pro-image-preview",
  "prompt": "一张空白的图",
  "response_format": "b64_json",
  "size": "1024x1024",
  "quality": "standard",
  "n": 1
}'

返回格式:
{
"data": [
{
"b64_json": "/9j/4AAQSkZJRgABAQEBLAEsAAD/6xdoSlAAAQAAAAEAABdeanVtYgAA...{2.2M}...=="
}
],
"created": 1764129295
}

image

Summary by CodeRabbit

  • New Features

    • Integrated Gemini image generation support, enabling users to generate images using Gemini-powered models
    • Added new Gemini image generation model variants to the platform's available models
  • Improvements

    • Optimized API response serialization for cleaner output formatting

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Nov 26, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This pull request adds Gemini image generation support by introducing image sizing and quality mapping logic, new image response conversion functions, HTTP handlers for image responses, and extends the list of supported Gemini image models. JSON serialization is also refined for image data fields to omit empty values.

Changes

Cohort / File(s) Summary
JSON serialization refinement
dto/openai_image.go
Updated JSON field tags for Url, B64Json, and RevisedPrompt to include omitempty, ensuring empty image data fields are excluded from JSON output
Gemini image generation sizing and config
relay/channel/gemini/adaptor.go
Added ImageConfig, SizeMapping, and QualityMapping types to map image sizes and quality levels. Implemented processSizeParameters helper and size mapping logic. Extended ConvertImageRequest to handle Gemini image requests (gemini-3-pro-image) by converting to GeneralOpenAIRequest with custom ExtraBody. Added response routing for Gemini image responses via ChatImageHandler in DoResponse
Gemini image response conversion and handling
relay/channel/gemini/relay-gemini.go
Added convertToOaiImageResponse function to extract inline images from Gemini chat responses and convert to OpenAI format. Added ChatImageHandler function to read, unmarshal, convert, and emit Gemini image responses with proper error handling
Gemini supported image models
setting/model_setting/gemini.go
Appended four new Gemini image models to the supported imagine models list: "gemini-3-pro-image-preview", "gemini-2.5-flash-image", "nano-banana", and "nano-banana-pro"

Sequence Diagram

sequenceDiagram
    participant Client
    participant Adaptor as Relay Adaptor
    participant GeminiAPI as Gemini API
    participant Handler as Image Handler
    participant Response as HTTP Response

    Client->>Adaptor: Image request (gemini-3-pro-image)
    Adaptor->>Adaptor: processSizeParameters<br/>(map size/quality)
    Adaptor->>Adaptor: Create GeneralOpenAIRequest<br/>with ExtraBody config
    Adaptor->>GeminiAPI: Forward request
    GeminiAPI-->>Adaptor: GeminiChatResponse<br/>(with inline image)
    Adaptor->>Handler: Route to ChatImageHandler
    Handler->>Handler: convertToOaiImageResponse<br/>(extract image data)
    Handler->>Response: Write OpenAI<br/>ImageResponse JSON
    Response-->>Client: Image response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Key areas for attention:
    • Size and quality mapping logic in adaptor.go — verify correct mapping between Gemini and OpenAI formats
    • ExtraBody JSON marshaling in ConvertImageRequest — ensure proper serialization of Google-specific generation_config
    • Image extraction logic in convertToOaiImageResponse — confirm handling of edge cases and error propagation
    • Integration point in DoResponse for routing image responses — verify the condition logic for triggering ChatImageHandler

Possibly related PRs

Poem

🐰 A fuzzy tail twitch of delight!
Gemini now paints with images bright,
Sizes mapped, responses aligned,
OpenAI format redefined,
Empty fields tucked out of sight! 🎨✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'OAI生图接口支持gemini 3 pro image preview' accurately describes the main change: adding support for Gemini 3 Pro image preview via the OAI-standard image generation endpoint, which aligns with the code changes across multiple files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@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)
relay/channel/gemini/adaptor.go (1)

98-129: Consider the interaction between size and quality parameters.

In processSizeParameters, when both size and quality are provided, the quality parameter will always overwrite the ImageSize field, even if size already set it via getSizeMappings. For example:

  • size="2048x2048" sets ImageSize="2K"
  • quality="hd" then overwrites it to "2K" (same value in this case, but the logic unconditionally overwrites)

If the intent is for quality to override size-based imageSize, this is fine. Otherwise, consider only setting ImageSize from quality when it wasn't already set by size.

If quality should only apply when size didn't set imageSize:

 	if quality != "" {
+		if config.ImageSize == "" {
 			qualityMapping := getImageSizeMapping()
 			switch strings.ToLower(strings.TrimSpace(quality)) {
 			case "hd", "high":
 				config.ImageSize = qualityMapping.HD
 			case "4k":
 				config.ImageSize = qualityMapping.FourK
 			case "standard", "medium", "low", "auto", "1k":
 				config.ImageSize = qualityMapping.Standard
 			}
+		}
 	}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a6a20a2 and d859872.

📒 Files selected for processing (4)
  • dto/openai_image.go (1 hunks)
  • relay/channel/gemini/adaptor.go (4 hunks)
  • relay/channel/gemini/relay-gemini.go (1 hunks)
  • setting/model_setting/gemini.go (1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: RedwindA
Repo: QuantumNous/new-api PR: 1537
File: relay/gemini_handler.go:330-342
Timestamp: 2025-08-08T17:12:43.157Z
Learning: In the new-api repository, the `GeminiEmbeddingHandler` function in `relay/gemini_handler.go` is designed specifically for native Gemini embedding requests and therefore does not require the `ConvertGeminiRequest` step that is used in the chat handler. The embedding requests are already in the native Gemini format and don't need conversion.
📚 Learning: 2025-08-04T14:36:34.528Z
Learnt from: antecanis8
Repo: QuantumNous/new-api PR: 1500
File: relay/channel/gemini/adaptor.go:0-0
Timestamp: 2025-08-04T14:36:34.528Z
Learning: All currently serviced Gemini embedding models support the outputDimensionality parameter, not just specific models like text-embedding-004.

Applied to files:

  • setting/model_setting/gemini.go
📚 Learning: 2025-08-05T17:14:17.246Z
Learnt from: neotf
Repo: QuantumNous/new-api PR: 1511
File: setting/ratio_setting/model_ratio.go:118-123
Timestamp: 2025-08-05T17:14:17.246Z
Learning: Claude models handle "-thinking" variants differently from Gemini models. For Claude models, only the base model (without "-thinking") gets an entry in defaultModelRatio map. The "-thinking" variants rely on the Claude relay handler stripping the suffix using strings.TrimSuffix(textRequest.Model, "-thinking") before looking up the ratio, so they automatically use the base model's ratio.

Applied to files:

  • setting/model_setting/gemini.go
📚 Learning: 2025-08-08T17:12:43.157Z
Learnt from: RedwindA
Repo: QuantumNous/new-api PR: 1537
File: relay/gemini_handler.go:330-342
Timestamp: 2025-08-08T17:12:43.157Z
Learning: In the new-api repository, the `GeminiEmbeddingHandler` function in `relay/gemini_handler.go` is designed specifically for native Gemini embedding requests and therefore does not require the `ConvertGeminiRequest` step that is used in the chat handler. The embedding requests are already in the native Gemini format and don't need conversion.

Applied to files:

  • relay/channel/gemini/relay-gemini.go
  • relay/channel/gemini/adaptor.go
📚 Learning: 2025-06-21T03:37:41.726Z
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.

Applied to files:

  • relay/channel/gemini/relay-gemini.go
🧬 Code graph analysis (2)
relay/channel/gemini/relay-gemini.go (9)
dto/gemini.go (1)
  • GeminiChatResponse (342-346)
dto/openai_image.go (2)
  • ImageResponse (166-170)
  • ImageData (171-175)
common/utils.go (1)
  • GetTimestamp (266-268)
relay/common/relay_info.go (1)
  • RelayInfo (76-123)
dto/openai_response.go (1)
  • Usage (222-240)
types/error.go (2)
  • NewAPIError (87-95)
  • NewOpenAIError (226-249)
service/http.go (1)
  • CloseResponseBodyGracefully (15-23)
common/constants.go (1)
  • DebugEnabled (71-71)
common/json.go (2)
  • Unmarshal (9-11)
  • Marshal (21-23)
relay/channel/gemini/adaptor.go (4)
dto/openai_request.go (2)
  • GeneralOpenAIRequest (26-98)
  • Message (282-293)
common/json.go (1)
  • Marshal (21-23)
setting/model_setting/gemini.go (1)
  • IsGeminiModelSupportImagine (68-75)
relay/channel/gemini/relay-gemini.go (1)
  • ChatImageHandler (1292-1333)
🔇 Additional comments (8)
dto/openai_image.go (1)

172-174: LGTM! Good practice adding omitempty tags.

Adding omitempty to these optional fields ensures cleaner JSON serialization by omitting empty values. This is especially useful when only one response format (url or b64_json) is used.

relay/channel/gemini/relay-gemini.go (2)

1268-1290: LGTM! Clean image extraction logic.

The function correctly extracts inline image data from Gemini chat response candidates and converts to the OpenAI image response format. Error handling for missing images is appropriate.


1292-1333: LGTM! Handler follows established patterns.

The implementation is consistent with other handlers in this file (GeminiChatHandler, GeminiEmbeddingHandler) in terms of error handling, response body reading, JSON marshaling, and usage metadata extraction.

relay/channel/gemini/adaptor.go (4)

59-85: LGTM! Clean type definitions for image configuration.

The types and quality mapping helper provide a clear structure for managing image generation parameters.


87-96: LGTM! Size mappings align with common image dimensions.

The mappings correctly translate standard image sizes to aspect ratios and imageSize values.


164-165: LGTM! Proper use of the size mappings helper.

The updated code correctly uses the getSizeMappings helper function.


346-348: LGTM! Correct routing for Gemini imagine models.

The routing logic properly directs requests for Gemini imagine-capable models to the new ChatImageHandler.

setting/model_setting/gemini.go (1)

29-32: The model names "nano-banana" and "nano-banana-pro" are legitimate Google Gemini model names, not placeholders.

Web search confirms these are official model names from Google: "Nano Banana" refers to the Gemini 2.5 Flash Image model, and "Nano Banana Pro" refers to the Gemini 3 Pro Image model. These appear in official Google and DeepMind announcements. The naming convention, while informal, is authentic. The code addition is valid.

Comment on lines +132 to 155
if strings.HasPrefix(info.UpstreamModelName, "gemini-3-pro-image") {
chatRequest := dto.GeneralOpenAIRequest{
Model: request.Model,
Messages: []dto.Message{
{Role: "user", Content: request.Prompt},
},
N: int(request.N),
}

config := processSizeParameters(strings.TrimSpace(request.Size), request.Quality)
googleGenerationConfig := map[string]interface{}{
"response_modalities": []string{"TEXT", "IMAGE"},
"image_config": config,
}

extraBody := map[string]interface{}{
"google": map[string]interface{}{
"generation_config": googleGenerationConfig,
},
}
chatRequest.ExtraBody, _ = json.Marshal(extraBody)

return a.ConvertOpenAIRequest(c, info, &chatRequest)
}

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

Handle json.Marshal error on Line 152.

The error from json.Marshal(extraBody) is silently ignored with _. If marshaling fails, chatRequest.ExtraBody will be nil, and the critical image configuration won't be sent to the upstream API, likely causing the request to fail or return unexpected results.

Apply this diff to handle the error:

-		chatRequest.ExtraBody, _ = json.Marshal(extraBody)
+		extraBodyBytes, err := json.Marshal(extraBody)
+		if err != nil {
+			return nil, fmt.Errorf("failed to marshal extra body: %w", err)
+		}
+		chatRequest.ExtraBody = extraBodyBytes
🤖 Prompt for AI Agents
In relay/channel/gemini/adaptor.go around lines 132 to 155,
json.Marshal(extraBody) is called and its error is ignored; capture the returned
error, and if non-nil log the error (with context) and return an appropriate
error Up the stack instead of proceeding with a nil ExtraBody. Modify the code
to assign the marshal result and err to variables, check err, call the component
logger (or return a wrapped error) and abort the function flow so the request is
not sent without the critical image configuration.

@creamlike1024
creamlike1024 merged commit 5ac1d02 into QuantumNous:main Nov 26, 2025
ennnnny pushed a commit to ennnnny/new-api that referenced this pull request Mar 17, 2026
…pro-image-preview-oai

OAI生图接口支持gemini 3 pro image preview
@coderabbitai coderabbitai Bot mentioned this pull request May 15, 2026
7 of 10 tasks
JacksonsY added a commit to JacksonsY/new-api that referenced this pull request Jul 20, 2026
Gemini 原生图片模型(nano-banana / *-flash-image / *-pro-image)只能靠 chat generateContent + responseModalities 出图,此前经 /v1/images/generations 会被 gemini 适配器以「仅支持 imagen」拒绝。本提交复刻上游被回滚的 QuantumNous#2305 并适配本仓:

- ConvertImageRequest 对 imagine 模型把 images 请求转成 chat 请求,交由 OpenAI→Gemini 转换(按映射后的上游模型名自动注入 responseModalities);DoResponse 新增 ChatImageHandler 把 generateContent 内联图转回 data[].b64_json。
- 仅在 RelayMode==ImagesGenerations 时生效,避免误伤这些模型的 chat 补全响应。
- 尺寸仅映射 aspect_ratio,不透传 imageSize(gemini-2.5-flash-image 会拒绝该参数)。
- JSON 统一走 common.Marshal;补 nano-banana/nano-banana-pro 到 SupportedImagineModels。

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
…pro-image-preview-oai

OAI生图接口支持gemini 3 pro image preview
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
…pro-image-preview-oai

OAI生图接口支持gemini 3 pro image preview
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.

2 participants