From 3f7a0f91ff210cd37e4991fd93dbbe7fa93fbbfd Mon Sep 17 00:00:00 2001 From: lindahao Date: Sat, 8 Aug 2026 23:34:56 +0800 Subject: [PATCH] fix: pass multi-reference video images and enable free video 1.5 Console/Build adapters now map multiple input images to official reference_images instead of rejecting anything beyond a single start frame. Build account capability normalization keeps grok-imagine-video-1.5 for free accounts on the primary Build path. --- .../application/model/service_test.go | 18 ++- .../internal/infra/provider/cli/adapter.go | 14 +- .../infra/provider/cli/adapter_test.go | 30 ++-- backend/internal/infra/provider/cli/video.go | 30 +++- .../internal/infra/provider/cli/video_test.go | 130 ++++++++++++++++-- .../infra/provider/console/console_test.go | 65 +++++++++ .../internal/infra/provider/console/media.go | 25 +++- 7 files changed, 263 insertions(+), 49 deletions(-) diff --git a/backend/internal/application/model/service_test.go b/backend/internal/application/model/service_test.go index 3bc6a3d8..7000b87f 100644 --- a/backend/internal/application/model/service_test.go +++ b/backend/internal/application/model/service_test.go @@ -260,8 +260,8 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) { assertSupports(superPrimary.ID, video15, true) assertSupports(superFallback.ID, video15, true) - assertSupports(freeAccount.ID, video15, false) - assertSupports(unknownAccount.ID, video15, false) + assertSupports(freeAccount.ID, video15, true) + assertSupports(unknownAccount.ID, video15, true) assertSupports(superPrimary.ID, "grok-4.5", true) assertSupports(superFallback.ID, "grok-code-fast-1", true) assertSupports(freeAccount.ID, "grok-4.5", true) @@ -374,11 +374,12 @@ type buildCapabilityNormalizerAdapter struct { } func (a *buildCapabilityNormalizerAdapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string { - // Match cli.Adapter rules: Build OAuth adds Composer; Super (paid or - // entitlement) ensures 1.5; otherwise remove video 1.5 exactly. + // Match cli.Adapter rules: Build OAuth adds Composer; all Build accounts + // ensure video 1.5 so Free can schedule grok-imagine-video-1.5. + _ = billing const video15 = "grok-imagine-video-1.5" - super := account.IsBuildSuper(credential, billing) - composer := credential.Provider == account.ProviderBuild && credential.AuthType == account.AuthTypeOAuth + buildAccount := credential.Provider == account.ProviderBuild + composer := buildAccount && credential.AuthType == account.AuthTypeOAuth result := make([]string, 0, len(models)+2) seen := make(map[string]struct{}, len(models)+2) hasVideo15 := false @@ -390,15 +391,12 @@ func (a *buildCapabilityNormalizerAdapter) NormalizeAccountModelCapabilities(mod continue } if modelName == video15 { - if !super { - continue - } hasVideo15 = true } seen[modelName] = struct{}{} result = append(result, modelName) } - if super && !hasVideo15 { + if buildAccount && !hasVideo15 { result = append(result, video15) } if composer { diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index f172208c..5d637369 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -619,11 +619,12 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential) // NormalizeAccountModelCapabilities normalizes capabilities that the OAuth // session contract exposes independently of the account's sparse /models list. // Composer is available to Build OAuth sessions even though the live catalog can -// return only grok-4.5. Super always includes video 1.5; Free and Unknown remove -// video 1.5 exactly. BuildAPIFallback is ignored. +// return only grok-4.5. Build accounts always include video 1.5 so Free can use +// grok-imagine-video-1.5 on the primary Build path. BuildAPIFallback is ignored. func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string { - super := account.IsBuildSuper(credential, billing) - composer := credential.Provider == account.ProviderBuild && credential.AuthType == account.AuthTypeOAuth + _ = billing + buildAccount := credential.Provider == account.ProviderBuild + composer := buildAccount && credential.AuthType == account.AuthTypeOAuth result := make([]string, 0, len(models)+2) seen := make(map[string]struct{}, len(models)+2) hasVideo15 := false @@ -636,15 +637,12 @@ func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *ac continue } if model == buildVideoModel { - if !super { - continue - } hasVideo15 = true } seen[model] = struct{}{} result = append(result, model) } - if super && !hasVideo15 { + if buildAccount && !hasVideo15 { result = append(result, buildVideoModel) } if composer { diff --git a/backend/internal/infra/provider/cli/adapter_test.go b/backend/internal/infra/provider/cli/adapter_test.go index f0cac0c2..16227d65 100644 --- a/backend/internal/infra/provider/cli/adapter_test.go +++ b/backend/internal/infra/provider/cli/adapter_test.go @@ -566,7 +566,7 @@ func TestGetBillingUsesCreditsAndLiveSubscriptionTier(t *testing.T) { } } -func TestNormalizeAccountModelCapabilitiesSuperAddsVideo15(t *testing.T) { +func TestNormalizeAccountModelCapabilitiesBuildAddsVideo15(t *testing.T) { adapter := &Adapter{} build := account.Credential{Provider: account.ProviderBuild} // Super / paid: add 1.5 even when primary Build returns only grok-4.5. @@ -583,16 +583,21 @@ func TestNormalizeAccountModelCapabilitiesSuperAddsVideo15(t *testing.T) { if len(got) != 3 || got[0] != "grok-4.5" || got[1] != buildVideoModel || got[2] != "grok-code-fast-1" { t.Fatalf("super catalog = %#v", got) } - // Free: remove 1.5 even when the catalog exposes it. + // Free: keep/add 1.5 so free Build accounts can use video generation. got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5", buildVideoModel}, &account.Billing{Used: 1, PlanName: "free"}, build) - if len(got) != 1 || got[0] != "grok-4.5" { + if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel { t.Fatalf("free catalog = %#v", got) } - // Unknown (no Billing): treat as Free and remove 1.5. + // Unknown (no Billing): still keep 1.5 for Build accounts. got = adapter.NormalizeAccountModelCapabilities([]string{buildVideoModel, "grok-4.5"}, nil, build) - if len(got) != 1 || got[0] != "grok-4.5" { + if len(got) != 2 || got[0] != buildVideoModel || got[1] != "grok-4.5" { t.Fatalf("unknown catalog = %#v", got) } + // Free catalog without 1.5: inject it. + got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, &account.Billing{PlanName: "free"}, build) + if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel { + t.Fatalf("free inject catalog = %#v", got) + } // Do not depend on BuildAPIFallback; an empty catalog with Billing Super adds only 1.5. got = adapter.NormalizeAccountModelCapabilities(nil, &account.Billing{PlanName: "SuperGrok", CreditUsagePercent: 1}, build) if len(got) != 1 || got[0] != buildVideoModel { @@ -610,11 +615,11 @@ func TestNormalizeAccountModelCapabilitiesAddsComposerOnlyForBuildOAuth(t *testi adapter := &Adapter{} oauth := account.Credential{Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth} got := adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, &account.Billing{PlanName: "free"}, oauth) - if len(got) != 2 || got[0] != "grok-4.5" || got[1] != modeldomain.GrokComposer25Fast { + if len(got) != 3 || got[0] != "grok-4.5" || got[1] != buildVideoModel || got[2] != modeldomain.GrokComposer25Fast { t.Fatalf("OAuth Free capabilities = %#v", got) } got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5", modeldomain.GrokComposer25Fast, modeldomain.GrokComposer25Fast}, nil, oauth) - if len(got) != 2 || got[0] != "grok-4.5" || got[1] != modeldomain.GrokComposer25Fast { + if len(got) != 3 || got[0] != "grok-4.5" || got[1] != modeldomain.GrokComposer25Fast || got[2] != buildVideoModel { t.Fatalf("Composer capability was not deduplicated: %#v", got) } for _, credential := range []account.Credential{ @@ -622,8 +627,15 @@ func TestNormalizeAccountModelCapabilitiesAddsComposerOnlyForBuildOAuth(t *testi {Provider: account.ProviderWeb, AuthType: account.AuthTypeOAuth}, } { got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, nil, credential) - if len(got) != 1 || got[0] != "grok-4.5" { - t.Fatalf("Composer leaked outside Build OAuth for %#v: %#v", credential, got) + switch credential.Provider { + case account.ProviderBuild: + if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel { + t.Fatalf("Build SSO capabilities = %#v", got) + } + default: + if len(got) != 1 || got[0] != "grok-4.5" { + t.Fatalf("Composer leaked outside Build OAuth for %#v: %#v", credential, got) + } } } } diff --git a/backend/internal/infra/provider/cli/video.go b/backend/internal/infra/provider/cli/video.go index 672e0a6d..7a707def 100644 --- a/backend/internal/infra/provider/cli/video.go +++ b/backend/internal/infra/provider/cli/video.go @@ -14,6 +14,7 @@ import ( "unicode/utf8" "github.com/chenyme/grok2api/backend/internal/domain/account" + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" ) @@ -21,7 +22,9 @@ import ( const ( buildVideoModel = "grok-imagine-video-1.5" xaiVideoModel = "grok-imagine-video-1.5-preview" - buildVideoMaxImages = 1 + // Align with the gateway ceiling and official xAI video inputs: + // one start frame via image, or multiple references via reference_images. + buildVideoMaxImages = mediadomain.MaxInputImages buildVideoPollEvery = 2 * time.Second buildVideoMaxBodySize = 2 << 20 buildVideoErrorSummaryLimit = 256 @@ -148,13 +151,13 @@ func boundDiagnosticText(value string, limit int) string { } // GenerateVideo 通过 Build OAuth 创建并轮询视频任务;对外仍使用 grok-imagine-video-1.5, -// 发往 XAI 时仅在出站协议层转换为官方 preview 模型与 image.url 结构。 -// 最多 1 张首图;多于 1 张在调用上游前失败,不静默截断。 +// 发往 XAI 时仅在出站协议层转换为官方 preview 模型与 image/reference_images 结构。 +// 1 张图映射为 image;多张图映射为 reference_images。超过网关上限时失败,不静默截断。 // 显式模式优先;auto 下仅已确认 Super 且 bot_flag_source/bfs 为 1 或 2 默认使用 XAI。 // 其他 auto Super 账号仅在当次 Build 创建返回 403 后探测 XAI。 func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) { if len(request.ReferenceURLs) > buildVideoMaxImages { - return provider.VideoResult{}, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 1 张首图,当前为 %d 张", len(request.ReferenceURLs)) + return provider.VideoResult{}, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 %d 张参考图,当前为 %d 张", buildVideoMaxImages, len(request.ReferenceURLs)) } accessToken, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) if err != nil { @@ -291,16 +294,31 @@ func videoCreatePayload(request provider.VideoRequest, uploadURL string, profile if resolution := strings.TrimSpace(request.Resolution); resolution != "" { payload["resolution"] = resolution } - if len(request.ReferenceURLs) == 1 { + switch len(request.ReferenceURLs) { + case 0: + // text-to-video + case 1: imageURL := strings.TrimSpace(request.ReferenceURLs[0]) if imageURL == "" { return nil, fmt.Errorf("视频首图 URL 不能为空") } payload["image"] = map[string]any{profile.imageURLField: imageURL} + default: + references := make([]map[string]any, 0, len(request.ReferenceURLs)) + for _, rawURL := range request.ReferenceURLs { + imageURL := strings.TrimSpace(rawURL) + if imageURL == "" { + return nil, fmt.Errorf("视频参考图 URL 不能为空") + } + references = append(references, map[string]any{profile.imageURLField: imageURL}) + } + payload["reference_images"] = references } if _, hasPrompt := payload["prompt"]; !hasPrompt { if _, hasImage := payload["image"]; !hasImage { - return nil, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + if _, hasReferences := payload["reference_images"]; !hasReferences { + return nil, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + } } } if uploadURL = strings.TrimSpace(uploadURL); uploadURL != "" { diff --git a/backend/internal/infra/provider/cli/video_test.go b/backend/internal/infra/provider/cli/video_test.go index ebd2f822..9060652c 100644 --- a/backend/internal/infra/provider/cli/video_test.go +++ b/backend/internal/infra/provider/cli/video_test.go @@ -108,23 +108,69 @@ func TestXAIVideoCreatePayloadMatchesOfficialSchema(t *testing.T) { } } -func TestGenerateVideoRejectsTwoImagesBeforeUpstream(t *testing.T) { - adapter, encrypted := newTestBuildVideoAdapter(t) - var hits atomic.Int32 - adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { - hits.Add(1) - t.Fatalf("two-image request must not reach upstream: %s %s", request.Method, request.URL) - return nil, nil - }) - _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ - Credential: account.Credential{ID: 1, EncryptedAccessToken: encrypted}, - Prompt: "animate", +func TestBuildVideoCreatePayloadMapsMultipleReferences(t *testing.T) { + payload, err := videoCreatePayload(provider.VideoRequest{ + Prompt: "animate", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ReferenceURLs: []string{ + "https://cdn.example.com/one.png", + "https://cdn.example.com/two.png", + "https://cdn.example.com/three.png", + }, + }, "", buildVideoRequestProfile) + if err != nil { + t.Fatal(err) + } + if _, exists := payload["image"]; exists { + t.Fatalf("multi-reference payload must not include image: %#v", payload) + } + references, ok := payload["reference_images"].([]map[string]any) + if !ok || len(references) != 3 { + t.Fatalf("reference_images = %#v", payload["reference_images"]) + } + if references[0]["image_url"] != "https://cdn.example.com/one.png" || references[2]["image_url"] != "https://cdn.example.com/three.png" { + t.Fatalf("reference_images = %#v", references) + } + + xaiPayload, err := videoCreatePayload(provider.VideoRequest{ + Prompt: "animate", ReferenceURLs: []string{ "https://cdn.example.com/one.png", "https://cdn.example.com/two.png", }, + }, "https://api.example/v1/media/uploads/tok", xaiVideoRequestProfile) + if err != nil { + t.Fatal(err) + } + xaiReferences, ok := xaiPayload["reference_images"].([]map[string]any) + if !ok || len(xaiReferences) != 2 || xaiReferences[0]["url"] != "https://cdn.example.com/one.png" { + t.Fatalf("xai reference_images = %#v", xaiPayload["reference_images"]) + } + if _, exists := xaiPayload["image"]; exists { + t.Fatalf("xai multi-reference payload must not include image: %#v", xaiPayload) + } +} + +func TestGenerateVideoRejectsTooManyImagesBeforeUpstream(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + var hits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + hits.Add(1) + t.Fatalf("oversized reference request must not reach upstream: %s %s", request.Method, request.URL) + return nil, nil }) - if err == nil || !strings.Contains(err.Error(), "最多支持 1 张首图") { + references := make([]string, buildVideoMaxImages+1) + for i := range references { + references[i] = "https://cdn.example.com/" + strings.Repeat("x", i+1) + ".png" + } + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{ID: 1, EncryptedAccessToken: encrypted}, + Prompt: "animate", + ReferenceURLs: references, + }) + if err == nil || !strings.Contains(err.Error(), "最多支持") { t.Fatalf("error = %v", err) } if hits.Load() != 0 { @@ -132,6 +178,66 @@ func TestGenerateVideoRejectsTwoImagesBeforeUpstream(t *testing.T) { } } +func TestGenerateVideoPostsReferenceImagesAndPollsUntilReady(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + var createBody map[string]any + var pollCount atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if identity := infraegress.AccountFromContext(request.Context()); identity != "grok_build_9" { + t.Fatalf("egress account identity = %q", identity) + } + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + if request.Header.Get("Authorization") != "Bearer access-token" { + t.Fatalf("missing auth header: %#v", request.Header) + } + if err := json.NewDecoder(request.Body).Decode(&createBody); err != nil { + t.Fatal(err) + } + return jsonResponse(http.StatusOK, `{"request_id":"vid_ref_123","status":"queued"}`, request), nil + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/vid_ref_123": + count := pollCount.Add(1) + if count == 1 { + return jsonResponse(http.StatusOK, `{"status":"processing","progress":40}`, request), nil + } + return jsonResponse(http.StatusOK, `{"status":"completed","progress":100,"video":{"url":"https://assets.grok.com/videos/ref.mp4"}}`, request), nil + default: + t.Fatalf("unexpected request %s %s", request.Method, request.URL) + return nil, nil + } + }) + + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{ID: 9, UserID: "user-1", EncryptedAccessToken: encrypted}, + Prompt: "animate knife", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ReferenceURLs: []string{ + "https://r2.example.com/first.png", + "https://r2.example.com/second.png", + }, + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://assets.grok.com/videos/ref.mp4" || result.ContentType != "video/mp4" { + t.Fatalf("result = %#v", result) + } + if _, exists := createBody["image"]; exists { + t.Fatalf("create body unexpectedly includes image: %#v", createBody) + } + references, ok := createBody["reference_images"].([]any) + if !ok || len(references) != 2 { + t.Fatalf("create body reference_images = %#v", createBody["reference_images"]) + } + first, _ := references[0].(map[string]any) + second, _ := references[1].(map[string]any) + if first["image_url"] != "https://r2.example.com/first.png" || second["image_url"] != "https://r2.example.com/second.png" { + t.Fatalf("create body = %#v", createBody) + } +} + func TestGenerateVideoPostsSingleImageAndPollsUntilReady(t *testing.T) { adapter, encrypted := newTestBuildVideoAdapter(t) var createBody map[string]any diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index bb88af56..23df3ab8 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -1266,6 +1266,71 @@ func TestConsoleVideoCreatesAndPollsStandardResources(t *testing.T) { } } +func TestConsoleVideoPostsReferenceImages(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if _, exists := payload["image"]; exists { + t.Errorf("multi-reference payload must not include image: %#v", payload) + } + references, ok := payload["reference_images"].([]any) + if !ok || len(references) != 3 { + t.Errorf("reference_images = %#v", payload["reference_images"]) + } else { + first, _ := references[0].(map[string]any) + third, _ := references[2].(map[string]any) + if first["url"] != "https://example.com/a.png" || third["url"] != "https://example.com/c.png" { + t.Errorf("reference_images = %#v", references) + } + } + _, _ = writer.Write([]byte(`{"request_id":"upstream-video-ref-1"}`)) + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-ref-1": + _, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-ref.mp4"}}`)) + default: + http.NotFound(writer, request) + } + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p", + ReferenceURLs: []string{ + "https://example.com/a.png", + "https://example.com/b.png", + "https://example.com/c.png", + }, + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://vidgen.x.ai/result-ref.mp4" || result.ContentType != "video/mp4" { + t.Fatalf("video result = %#v", result) + } +} + +func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) { + adapter, credential := newConsoleTestAdapter(t, "https://console.example") + references := make([]string, consoleMaxVideoImages+1) + for i := range references { + references[i] = "https://example.com/" + strings.Repeat("x", i+1) + ".png" + } + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "animate", Duration: 6, ReferenceURLs: references, + }) + if err == nil || !strings.Contains(err.Error(), "最多支持") { + t.Fatalf("error = %v", err) + } +} + func TestParseConsoleVideoStatusRejectsUnknownState(t *testing.T) { if _, _, err := parseConsoleVideoStatus([]byte(`{"status":"mystery"}`), nil); err == nil || !strings.Contains(err.Error(), "状态无效") { t.Fatalf("unknown status error = %v", err) diff --git a/backend/internal/infra/provider/console/media.go b/backend/internal/infra/provider/console/media.go index 21d358a5..1f0edb71 100644 --- a/backend/internal/infra/provider/console/media.go +++ b/backend/internal/infra/provider/console/media.go @@ -29,7 +29,9 @@ const ( consoleMediaOutputAttempts = 3 consoleVideoPollEvery = 2 * time.Second consoleMaxEditImages = 3 - consoleMaxVideoImages = 1 + // Align with the gateway ceiling and official xAI video inputs: + // one start frame via image, or multiple references via reference_images. + consoleMaxVideoImages = mediadomain.MaxInputImages ) type consoleMediaUpstreamError struct { @@ -398,7 +400,7 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque return provider.VideoResult{}, errors.New("Console 视频模型未注册") } if len(request.ReferenceURLs) > consoleMaxVideoImages { - return provider.VideoResult{}, fmt.Errorf("Console grok-imagine-video 最多支持 1 张首图,当前为 %d 张", len(request.ReferenceURLs)) + return provider.VideoResult{}, fmt.Errorf("Console grok-imagine-video 最多支持 %d 张参考图,当前为 %d 张", consoleMaxVideoImages, len(request.ReferenceURLs)) } if request.Duration < 1 || request.Duration > 15 { return provider.VideoResult{}, errors.New("duration 必须在 1 到 15 秒之间") @@ -418,16 +420,31 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque if resolution := strings.TrimSpace(request.Resolution); resolution != "" { payload["resolution"] = resolution } - if len(request.ReferenceURLs) == 1 { + switch len(request.ReferenceURLs) { + case 0: + // text-to-video + case 1: value := strings.TrimSpace(request.ReferenceURLs[0]) if !validConsoleMediaInputURL(value, "image") { return provider.VideoResult{}, errors.New("视频首图必须是 HTTPS URL 或 image data URL") } payload["image"] = map[string]any{"url": value} + default: + references := make([]map[string]any, 0, len(request.ReferenceURLs)) + for _, rawURL := range request.ReferenceURLs { + value := strings.TrimSpace(rawURL) + if !validConsoleMediaInputURL(value, "image") { + return provider.VideoResult{}, errors.New("每张视频参考图都必须是 HTTPS URL 或 image data URL") + } + references = append(references, map[string]any{"url": value}) + } + payload["reference_images"] = references } if _, hasPrompt := payload["prompt"]; !hasPrompt { if _, hasImage := payload["image"]; !hasImage { - return provider.VideoResult{}, errors.New("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + if _, hasReferences := payload["reference_images"]; !hasReferences { + return provider.VideoResult{}, errors.New("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + } } }