Skip to content

feat(volcengine): Add support for image editing for Volcengine channel - #1442

Closed
0daysseus wants to merge 1 commit into
QuantumNous:mainfrom
0daysseus:main
Closed

feat(volcengine): Add support for image editing for Volcengine channel#1442
0daysseus wants to merge 1 commit into
QuantumNous:mainfrom
0daysseus:main

Conversation

@0daysseus

@0daysseus 0daysseus commented Jul 26, 2025

Copy link
Copy Markdown

This commit introduces support for the image editing feature (RelayModeImagesEdits) for the Volcengine channel. Previously, this functionality was not implemented.

The key changes include:

  • Refactored ConvertImageRequest to handle image edit requests by converting them to the application/json format required by the Volcengine API, instead of the incorrect multipart/form-data.
  • Implemented helper functions to process form fields, extract the uploaded image, and encode it to Base64 within the JSON payload.
  • Added support for additional Volcengine-specific parameters: seed, guidance_scale, and watermark.
  • Updated dto.ImageRequest and the image_handler to recognize and process these new parameters.
  • Corrected the request URL and headers for the image editing endpoint.

Summary by CodeRabbit

  • New Features

    • Added optional seed and guidance scale parameters for more customizable image generation.
    • Image edit requests now use JSON with base64-encoded images for better compatibility.
  • Bug Fixes

    • Enhanced parsing and validation of watermark, guidance scale, and seed parameters from form data to prevent errors.
  • Chores

    • Aligned request handling and headers with updated API specifications.

@coderabbitai

coderabbitai Bot commented Jul 26, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Two new fields, Seed and GuidanceScale, were added to the ImageRequest struct. The Volcengine image editing relay logic was refactored to accept JSON requests with base64-encoded images instead of multipart form data. The image handler was updated to parse and validate the new fields from incoming requests.

Changes

File(s) Change Summary
dto/dalle.go Added Seed (int) and GuidanceScale (float64) fields to ImageRequest struct.
relay/channel/volcengine/adaptor.go Refactored image edit relay to accept JSON with base64-encoded images; added helpers for form parsing, encoding. Updated request URL and headers accordingly.
relay/image_handler.go Updated to parse and validate guidance_scale (float64), seed (int), and watermark (bool) from multipart form data.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant APIHandler
    participant VolcengineAdaptor

    Client->>APIHandler: POST /image with multipart form (includes guidance_scale, seed)
    APIHandler->>APIHandler: Parse guidance_scale and seed
    APIHandler->>VolcengineAdaptor: ConvertImageRequest (with parsed fields)
    VolcengineAdaptor->>VolcengineAdaptor: Extract image, encode as base64
    VolcengineAdaptor->>VolcengineAdaptor: Build JSON request with fields and image
    VolcengineAdaptor->>APIHandler: Return JSON request
    APIHandler->>Volcengine: Forward JSON request
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

In the garden of code where the images grow,
Two new seeds—scale and seed—now gently sow.
With base64 magic and JSON delight,
Images journey in data-packed flight.
The relay now hums, a rabbit’s proud tune—
Hopping through fields, under a bright coding moon! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 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 generate unit tests to generate unit tests for 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.

@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: 4

🧹 Nitpick comments (2)
relay/image_handler.go (1)

56-63: Consider adding validation for guidance_scale range.

The parsing logic is correct, but you may want to validate that guidance_scale falls within an acceptable range for Volcengine's API to provide better error messages to users.

 guidanceScaleStr := formData.Get("guidance_scale")
 if guidanceScaleStr != "" {
     guidanceScale, err := strconv.ParseFloat(guidanceScaleStr, 64)
     if err != nil {
         return nil, fmt.Errorf("invalid guidance_scale parameter: %v", err)
     }
+    // Add validation based on Volcengine's API requirements
+    if guidanceScale < 0 || guidanceScale > 20 {
+        return nil, fmt.Errorf("guidance_scale must be between 0 and 20")
+    }
     imageRequest.GuidanceScale = guidanceScale
 }
relay/channel/volcengine/adaptor.go (1)

134-159: Consider making the file size limit configurable.

The 10MB file size limit is hardcoded. Consider making this configurable or at least documenting it in the function comment to help future maintainers.

+// fileHeaderToBase64 converts an uploaded file to a data URI string.
+// The maximum allowed file size is 10MB.
 func fileHeaderToBase64(fileHeader *multipart.FileHeader) (string, error) {
     // Define maximum allowed file size (10MB)
     const maxFileSize = 10 << 20 // 10MB
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4d0037a and 6703ec5.

📒 Files selected for processing (3)
  • dto/dalle.go (1 hunks)
  • relay/channel/volcengine/adaptor.go (3 hunks)
  • relay/image_handler.go (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
relay/image_handler.go (2)

Learnt from: feitianbubu
PR: #1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().

Learnt from: feitianbubu
PR: #1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().

🧬 Code Graph Analysis (2)
relay/image_handler.go (1)
common/str.go (1)
  • String2Int (63-69)
relay/channel/volcengine/adaptor.go (3)
relay/channel/adapter.go (1)
  • Adaptor (13-29)
relay/common/relay_info.go (1)
  • RelayInfo (62-112)
relay/channel/api_request.go (1)
  • SetupApiRequestHeader (23-35)
🔇 Additional comments (1)
dto/dalle.go (1)

19-20: LGTM! Well-structured field additions.

The new Seed and GuidanceScale fields are properly defined with appropriate types and JSON tags. The use of omitempty ensures backward compatibility for requests that don't include these optional parameters.

Comment thread relay/channel/volcengine/adaptor.go
Comment thread relay/channel/volcengine/adaptor.go
Comment on lines +195 to +202
case constant.RelayModeImagesEdits:
return info.BaseUrl + "/api/v3/images/generations", nil

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.

💡 Verification agent

🧩 Analysis chain

Verify that Volcengine uses the same endpoint for image generation and editing.

The change to use /api/v3/images/generations for both generation and editing modes should be verified against Volcengine's API documentation.


🌐 Web query:

What is the correct API endpoint for Volcengine image editing? Does Volcengine use the same endpoint for both image generation and image editing at /api/v3/images/generations?

💡 Result:

Volcengine provides APIs for both image generation and image editing, each with distinct endpoints. The endpoint /api/v3/images/generations is specifically designed for image generation tasks. For image editing functionalities, Volcengine offers the ImageX service, which includes various image processing capabilities.

To utilize the ImageX service, you can refer to the official documentation for detailed information on available endpoints and usage guidelines. (volcengine.com)

In summary, Volcengine uses separate endpoints for image generation and image editing, and the /api/v3/images/generations endpoint is dedicated to image generation tasks.

Citations:


Use the correct Volcengine image-editing endpoint

Volcengine’s /api/v3/images/generations endpoint only supports image generation. Image editing belongs to their separate ImageX service and must use a dedicated editing endpoint (see Volcengine docs¹).

Please update the code in relay/channel/volcengine/adaptor.go so that under case constant.RelayModeImagesEdits: you point to the proper ImageX edit URL instead of /api/v3/images/generations.

• File: relay/channel/volcengine/adaptor.go
• Lines: around 195–196

case constant.RelayModeImagesEdits:
-   return info.BaseUrl + "/api/v3/images/generations", nil
+   return info.BaseUrl + "<correct-editing-endpoint>", nil

¹ https://www.volcengine.com/docs/508/1263359?utm_source=openai

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In relay/channel/volcengine/adaptor.go around lines 195 to 196, the URL for the
case constant.RelayModeImagesEdits incorrectly points to the image generation
endpoint /api/v3/images/generations. Update this to use the correct Volcengine
ImageX service editing endpoint as specified in their documentation, replacing
the URL string with the dedicated image editing endpoint URL.

Comment thread relay/image_handler.go Outdated
Signed-off-by: 0daysseus <74554363+0daysseus@users.noreply.github.com>

@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: 0

♻️ Duplicate comments (2)
relay/channel/volcengine/adaptor.go (2)

86-113: Type-specific parsing addresses previous concerns, but watermark handling needs refinement.

This implementation correctly addresses the previous review comment about avoiding generic JSON parsing by explicitly handling known fields that require type conversion.

However, the watermark parsing on line 107 only treats "true" as true and everything else as false. This doesn't distinguish between explicit "false" and missing values, which could be problematic for API semantics.

Consider improving watermark parsing to handle explicit boolean values:

-case "watermark":
-    jsonRequest[key] = values[0] == "true"
+case "watermark":
+    if v, err := strconv.ParseBool(values[0]); err == nil {
+        jsonRequest[key] = v
+    }

201-202: Incorrect endpoint - this duplicates a previous review concern.

As noted in previous reviews, Volcengine uses separate endpoints for image generation and image editing. The /api/v3/images/generations endpoint is only for generation, not editing.

Please update to use the correct Volcengine ImageX service editing endpoint instead of reusing the generations endpoint.

🧹 Nitpick comments (1)
relay/channel/volcengine/adaptor.go (1)

39-62: Good refactoring to support JSON format for image editing.

The conversion from multipart form data to JSON format aligns with Volcengine's API requirements. The error handling and flow control are appropriate.

Consider making the maxMemory constant consistent with the file size limit used in fileHeaderToBase64 (10MB vs 32MB).

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6703ec5 and 15ec6af.

📒 Files selected for processing (3)
  • dto/dalle.go (1 hunks)
  • relay/channel/volcengine/adaptor.go (3 hunks)
  • relay/image_handler.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • dto/dalle.go
  • relay/image_handler.go
🔇 Additional comments (5)
relay/channel/volcengine/adaptor.go (5)

5-6: LGTM! Import additions support the new JSON conversion functionality.

The new imports (encoding/base64, encoding/json, strconv) are appropriately added to support the conversion from multipart form data to JSON with base64-encoded images.

Also applies to: 19-19


64-84: Well-structured helper function for building JSON requests.

The function clearly separates concerns by delegating to specific helper functions for form field processing and image extraction. The error handling is appropriate.


115-138: Comprehensive image file extraction with good fallback logic.

The function handles multiple common field naming conventions for image uploads, including array notation and indexed fields. The fallback mechanism ensures robust file detection.


140-165: Robust file processing with appropriate size limits and error handling.

The function properly enforces file size limits, handles file I/O operations safely with deferred cleanup, and creates correctly formatted data URI strings. The error messages are descriptive and helpful for debugging.


210-210: Appropriate Content-Type header for JSON requests.

Setting the Content-Type to application/json correctly supports the new JSON request format for image editing operations.

@0daysseus 0daysseus closed this Jul 29, 2025
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.

1 participant