Repository navigation
OAI生图接口支持gemini 3 pro image preview - #2305
creamlike1024 merged 2 commits into
Conversation
WalkthroughThis 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
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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.
Example instruction:
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. Comment |
There was a problem hiding this comment.
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 bothsizeandqualityare provided, the quality parameter will always overwrite theImageSizefield, even ifsizealready set it viagetSizeMappings. For example:
size="2048x2048"setsImageSize="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
📒 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.gorelay/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
omitemptyto 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
getSizeMappingshelper 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.
| 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) | ||
| } |
There was a problem hiding this comment.
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.
…pro-image-preview-oai OAI生图接口支持gemini 3 pro image preview
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]>
…pro-image-preview-oai OAI生图接口支持gemini 3 pro image preview
…pro-image-preview-oai OAI生图接口支持gemini 3 pro image preview
之前的gemini 3 pro image preview只支持在chat中生图, 现在增加在oai的标准生图接口的支持
请求格式:
返回格式:
{
"data": [
{
"b64_json": "/9j/4AAQSkZJRgABAQEBLAEsAAD/6xdoSlAAAQAAAAEAABdeanVtYgAA...{2.2M}...=="
}
],
"created": 1764129295
}
Summary by CodeRabbit
New Features
Improvements
✏️ Tip: You can customize this high-level summary in your review settings.