Skip to content

feat: add ali wan video - #2141

Merged
Calcium-Ion merged 8 commits into
QuantumNous:mainfrom
seefs001:pr-2139
Oct 31, 2025
Merged

Calcium-Ion merged 8 commits into
QuantumNous:mainfrom
seefs001:pr-2139

Conversation

@seefs001

@seefs001 seefs001 commented Oct 31, 2025 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

New Features

  • Added support for Ali (Alibaba) video generation platform with full request/response handling, task status tracking, and automatic model mapping
  • Added Gemini video URL resolution capability for video proxying

Improvements

  • Enhanced video task tracking with upstream and origin model name metadata
  • Optimized JSON-based request parsing for video generation endpoints
  • Improved form data processing with enhanced error handling

@coderabbitai

coderabbitai Bot commented Oct 31, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR adds support for Ali video generation tasks through a new channel adaptor, refactors form data handling to use a helper function, expands TaskSubmitReq with JSON unmarshalling support, enhances Task properties with upstream/origin model names, updates video proxy routing for Gemini and Ali channels, and modifies request validation to use JSON parsing.

Changes

Cohort / File(s) Summary
Ali Video Task Integration
relay/channel/task/ali/adaptor.go, relay/channel/task/ali/constants.go, relay/relay_adaptor.go
Introduces complete Ali video generation adaptor with request/response models, URL/header/body builders, status mapping, and integration wiring in GetTaskAdaptor
Form Data Handling Refactor
common/gin.go
Extracts form data processing into new processFormMap helper function; refactors parseFormData and parseMultipartFormData to marshal form maps to JSON and unmarshal into target values
Video Request/Response Models
dto/openai_video.go, relay/common/relay_info.go
Changes Metadata JSON tag from "meta_data" to "metadata"; expands TaskSubmitReq with Seconds and InputReference fields plus custom UnmarshalJSON for metadata parsing
Task Model Enhancements
model/task.go
Adds UpstreamModelName and OriginModelName fields to Properties struct; updates Scan/Value methods and InitTask to handle nil relayInfo and propagate model names
Video Proxy Channel Routing
controller/video_proxy.go
Replaces if-else with switch statement to handle Gemini and Ali channel types distinctly; adds getGeminiVideoURL resolution and per-channel header/URL configuration
Request Validation Update
relay/common/relay_utils.go
Replaces multipart form-data parsing in ValidateMultipartDirect with JSON-based unmarshalling; maps InputReference to Images and derives duration from Seconds or Duration field

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ValidateMultipartDirect as ValidateMultipartDirect<br/>(relay_utils.go)
    participant TaskSubmitReq as TaskSubmitReq<br/>(UnmarshalJSON)
    participant GetTaskAdaptor as GetTaskAdaptor<br/>(relay_adaptor.go)
    participant AliAdaptor as Ali TaskAdaptor<br/>(adaptor.go)
    participant AliAPI as Ali API
    
    Client->>ValidateMultipartDirect: POST video task request
    Note over ValidateMultipartDirect: Parse JSON body
    ValidateMultipartDirect->>TaskSubmitReq: Unmarshal into TaskSubmitReq
    TaskSubmitReq->>TaskSubmitReq: Custom UnmarshalJSON<br/>extracts metadata (string or object)
    ValidateMultipartDirect->>GetTaskAdaptor: ChannelTypeAli
    GetTaskAdaptor->>AliAdaptor: Instantiate Ali adaptor
    AliAdaptor->>AliAdaptor: Init, ValidateRequest
    AliAdaptor->>AliAdaptor: BuildRequestURL<br/>BuildRequestHeader<br/>BuildRequestBody
    AliAdaptor->>AliAPI: DoRequest (POST)
    AliAPI-->>AliAdaptor: Response with taskId, status
    AliAdaptor->>AliAdaptor: DoResponse (parse, map status)
    AliAdaptor-->>Client: OpenAI-format video response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Ali adaptor implementation — Substantial new code with multiple data models, request/response handling, and status mapping logic
  • Custom UnmarshalJSON in TaskSubmitReq — Non-trivial metadata parsing with fallback handling requires careful validation
  • Video proxy channel routing — New switch cases for Gemini and Ali require verification of per-channel logic correctness
  • Task model initialization — Enhanced InitTask with nil-safety checks and field propagation needs validation for edge cases
  • Form data refactor — While modular, impacts both regular and multipart parsing paths; ensure backward compatibility

Possibly related PRs

  • veo #1792 — Adds TaskAdaptor implementations (Vertex) and wires them in relay_adaptor, similar pattern to Ali adaptor integration
  • task_relay_info #1656 — Modifies RelayInfo structure and adaptor signatures for relay metadata centralization, overlaps with TaskSubmitReq expansion
  • Gemini渠道支持veo视频生成 #2075 — Updates video_proxy.go with Gemini channel-specific logic (URL resolution, headers), related to the video proxy changes here

Suggested reviewers

  • feitianbubu
  • xyfacai

Poem

🐰 Ali's tasks now flow through channels bright,
Form data marshals in JSON light,
Adaptors wire the relay's way,
New fields propagate without delay,
Video proxies route with grace,
Refactoring brings order to the place! 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "feat: add ali wan video" directly aligns with the primary objective of this changeset, which is to introduce support for Ali Wan video generation. The main changes include a complete new Ali adaptor module (relay/channel/task/ali/adaptor.go and constants.go), integration into the relay system (relay/relay_adaptor.go), and supporting modifications to request/response handling and task models. The title is concise, clear, and specific enough to immediately convey to a reviewer that this PR adds a new video generation capability for the Ali Wan service, with no misleading or off-topic elements.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • 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

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

@Calcium-Ion
Calcium-Ion merged commit ab30f58 into QuantumNous:main Oct 31, 2025

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
relay/common/relay_utils.go (1)

122-171: Don't drop client-requested size

size stays empty because we never assign req.Size into the local variable anymore. The Sora block then always overwrites it with 720x1280, so callers lose their requested resolution and we silently skip the validation meant to guard invalid sizes. Please propagate the parsed value before the defaults run.

-	model = req.Model
-	seconds, _ = strconv.Atoi(req.Seconds)
+	model = req.Model
+	size = req.Size
+	seconds, _ = strconv.Atoi(req.Seconds)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9629c8a and 1d172d0.

📒 Files selected for processing (9)
  • common/gin.go (4 hunks)
  • controller/video_proxy.go (2 hunks)
  • dto/openai_video.go (1 hunks)
  • model/task.go (2 hunks)
  • relay/channel/task/ali/adaptor.go (1 hunks)
  • relay/channel/task/ali/constants.go (1 hunks)
  • relay/common/relay_info.go (3 hunks)
  • relay/common/relay_utils.go (1 hunks)
  • relay/relay_adaptor.go (2 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: Sh1n3zZ
Repo: QuantumNous/new-api PR: 1659
File: relay/relay_task.go:285-305
Timestamp: 2025-08-26T09:59:00.337Z
Learning: In controller/task_video.go, the redactVideoResponseBody function sanitizes video task responses by removing bytesBase64Encoded fields and truncating base64 strings to 256 characters to prevent large binary data from being stored in task.Data.
📚 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:

  • controller/video_proxy.go
📚 Learning: 2025-08-26T09:59:00.337Z
Learnt from: Sh1n3zZ
Repo: QuantumNous/new-api PR: 1659
File: relay/relay_task.go:285-305
Timestamp: 2025-08-26T09:59:00.337Z
Learning: In controller/task_video.go, data: URLs (containing base64 encoded video data) are prevented from being stored in task.FailReason by checking if the URL starts with "data:" before assignment. This same pattern should be applied consistently across the codebase.

Applied to files:

  • controller/video_proxy.go
📚 Learning: 2025-08-26T09:59:00.337Z
Learnt from: Sh1n3zZ
Repo: QuantumNous/new-api PR: 1659
File: relay/relay_task.go:285-305
Timestamp: 2025-08-26T09:59:00.337Z
Learning: In controller/task_video.go, the redactVideoResponseBody function sanitizes video task responses by removing bytesBase64Encoded fields and truncating base64 strings to 256 characters to prevent large binary data from being stored in task.Data.

Applied to files:

  • controller/video_proxy.go
🧬 Code graph analysis (7)
relay/relay_adaptor.go (3)
constant/channel.go (1)
  • ChannelTypeAli (21-21)
relay/channel/task/ali/adaptor.go (1)
  • TaskAdaptor (107-111)
relay/channel/adapter.go (1)
  • TaskAdaptor (34-53)
model/task.go (2)
relay/common/relay_info.go (1)
  • ChannelMeta (56-74)
constant/channel.go (1)
  • ChannelTypeGemini (28-28)
relay/common/relay_utils.go (2)
relay/common/relay_info.go (1)
  • TaskSubmitReq (488-499)
common/gin.go (1)
  • UnmarshalBodyReusable (33-58)
relay/common/relay_info.go (1)
common/json.go (1)
  • Unmarshal (9-11)
common/gin.go (1)
common/json.go (2)
  • Unmarshal (9-11)
  • Marshal (21-23)
controller/video_proxy.go (1)
constant/channel.go (2)
  • ChannelTypeGemini (28-28)
  • ChannelTypeAli (21-21)
relay/channel/task/ali/adaptor.go (11)
model/task.go (9)
  • TaskStatus (13-13)
  • TaskStatusQueued (35-35)
  • TaskStatusInProgress (36-36)
  • TaskStatusSuccess (38-38)
  • TaskStatusFailure (37-37)
  • Task (42-63)
  • Task (297-301)
  • Task (303-307)
  • Properties (75-79)
relay/common/relay_info.go (3)
  • RelayInfo (76-123)
  • TaskSubmitReq (488-499)
  • TaskInfo (541-551)
relay/common/relay_utils.go (1)
  • ValidateMultipartDirect (110-176)
common/gin.go (1)
  • UnmarshalBodyReusable (33-58)
common/json.go (2)
  • Marshal (21-23)
  • Unmarshal (9-11)
relay/channel/api_request.go (1)
  • DoTaskApiRequest (301-323)
service/error.go (1)
  • TaskErrorWrapper (140-157)
dto/openai_video.go (7)
  • NewOpenAIVideo (43-47)
  • OpenAIVideoError (49-52)
  • VideoStatusQueued (10-10)
  • VideoStatusInProgress (11-11)
  • VideoStatusCompleted (12-12)
  • VideoStatusFailed (13-13)
  • VideoStatusUnknown (9-9)
common/utils.go (1)
  • GetTimestamp (266-268)
service/http_client.go (1)
  • GetHttpClient (49-51)
relay/channel/task/ali/constants.go (2)
  • ModelList (3-9)
  • ChannelName (11-11)

Comment on lines +4 to +9
"bytes"
"fmt"
"io"
"net/http"
"strings"

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

Hook up the new seconds field.

Right now req.Seconds is ignored, so clients that pass only seconds get a hard-coded 5‑second clip no matter what they asked for. Please parse the string and fall back to it whenever duration is zero.

@@
-import (
-	"bytes"
-	"fmt"
-	"io"
-	"net/http"
-	"strings"
+import (
+	"bytes"
+	"fmt"
+	"io"
+	"net/http"
+	"strconv"
+	"strings"
 )
@@
-	if req.Duration > 0 {
-		aliReq.Parameters.Duration = req.Duration
-	} else {
-		aliReq.Parameters.Duration = 5 // 默认5秒
-	}
+	duration := req.Duration
+	if duration == 0 {
+		trimmedSeconds := strings.TrimSpace(req.Seconds)
+		if trimmedSeconds != "" {
+			if parsed, err := strconv.Atoi(trimmedSeconds); err == nil {
+				duration = parsed
+			}
+		}
+	}
+	if duration > 0 {
+		aliReq.Parameters.Duration = duration
+	} else {
+		aliReq.Parameters.Duration = 5 // 默认5秒
+	}

Also applies to: 186-190

🤖 Prompt for AI Agents
In relay/channel/task/ali/adaptor.go around lines 4-9 (and also apply same fix
at lines 186-190), the new req.Seconds field is currently ignored causing a
default 5-second clip even when clients supply seconds; update the parsing logic
to read req.Seconds (string), parse it into an integer or duration (handle
strconv.Atoi or strconv.ParseFloat as appropriate), and if the parsed value is >
0 and the existing duration (from req.Duration or similar) is zero, set the clip
duration from the parsed seconds value; ensure to handle parse errors by falling
back to the default behavior and avoid panics by validating input.

Comment on lines +165 to +183
if req.Size != "" {
resolution := strings.ToUpper(req.Size)
// 支持 480p, 720p, 1080p 或 480P, 720P, 1080P
if !strings.HasSuffix(resolution, "P") {
resolution = resolution + "P"
}
aliReq.Parameters.Resolution = resolution
} else {
// 根据模型设置默认分辨率
if strings.HasPrefix(req.Model, "wan2.5") {
aliReq.Parameters.Resolution = "1080P"
} else if strings.HasPrefix(req.Model, "wan2.2-i2v-flash") {
aliReq.Parameters.Resolution = "720P"
} else if strings.HasPrefix(req.Model, "wan2.2-i2v-plus") {
aliReq.Parameters.Resolution = "1080P"
} else {
aliReq.Parameters.Resolution = "720P"
}
}

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 | 🔴 Critical

Stop treating size as a resolution.

Line 169 turns values such as "832*480" into "832*480P" and pushes them into parameters.resolution. Ali expects text-to-video payloads to carry that "832*480" value under parameters.size, so these requests are rejected even though the client supplied valid input. Please keep dimension-style tokens on size and reserve the resolution path for values that actually look like 480/720/1080p.

@@
-	if req.Size != "" {
-		resolution := strings.ToUpper(req.Size)
-		// 支持 480p, 720p, 1080p 或 480P, 720P, 1080P
-		if !strings.HasSuffix(resolution, "P") {
-			resolution = resolution + "P"
-		}
-		aliReq.Parameters.Resolution = resolution
-	} else {
+	if req.Size != "" {
+		rawSize := strings.TrimSpace(req.Size)
+		upperSize := strings.ToUpper(rawSize)
+		if strings.ContainsAny(upperSize, "X*") {
+			aliReq.Parameters.Size = rawSize
+		} else {
+			if !strings.HasSuffix(upperSize, "P") {
+				upperSize += "P"
+			}
+			aliReq.Parameters.Resolution = upperSize
+		}
+	} else {
🤖 Prompt for AI Agents
In relay/channel/task/ali/adaptor.go around lines 165 to 183, the code currently
treats any req.Size as a resolution (appending "P" and storing in
Parameters.Resolution), which corrupts dimension-style values like "832*480";
instead detect whether req.Size is a resolution token (e.g., matches digits
optionally followed by "P" or ends with "P" like 480/480P/720P/1080P) and only
then normalize/uppercase and write to aliReq.Parameters.Resolution; if req.Size
contains a dimension pattern (e.g., contains '*' or matches WIDTHxHEIGHT)
preserve it as-is and assign it to aliReq.Parameters.Size (do not append "P" or
change it), and if req.Size is empty keep the existing model-based
default-resolution logic unchanged.

ennnnny pushed a commit to ennnnny/new-api that referenced this pull request Mar 17, 2026
* feat: add ali wan video

* refactor: use same UnmarshalBodyReusable

* feat: enhance request body metadata

* feat: opt wan convertToOpenAIVideo

* feat: add wan support other param via json metadata

* refactor: remove unused code

* fix ali

---------

Co-authored-by: feitianbubu <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request May 20, 2026
8 of 11 tasks
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
* feat: add ali wan video

* refactor: use same UnmarshalBodyReusable

* feat: enhance request body metadata

* feat: opt wan convertToOpenAIVideo

* feat: add wan support other param via json metadata

* refactor: remove unused code

* fix ali

---------

Co-authored-by: feitianbubu <[email protected]>
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
* feat: add ali wan video

* refactor: use same UnmarshalBodyReusable

* feat: enhance request body metadata

* feat: opt wan convertToOpenAIVideo

* feat: add wan support other param via json metadata

* refactor: remove unused code

* fix ali

---------

Co-authored-by: feitianbubu <[email protected]>
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