mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 16:01:07 +00:00
fix: keep video image and reference_images semantics separate
Stop flattening image + reference_images into one list and coercing a single reference into the first-frame image field. Preserve official xAI mapping end-to-end across HTTP, gateway storage, Console, Build, and Web adapters.
This commit is contained in:
1 parent
aaf06e84b9
commit
17c5eaa77e
10 files changed
+421
-90
No files matched your search
@@ -40,13 +40,16 @@ func VideoInputFileReference(fileID string) string {
|
||||
}
|
||||
|
||||
type VideoInput struct {
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
Prompt string
|
||||
Duration int
|
||||
AspectRatio string
|
||||
Resolution string
|
||||
RequestID string
|
||||
ClientKey clientkey.Key
|
||||
PublicModel string
|
||||
Prompt string
|
||||
Duration int
|
||||
AspectRatio string
|
||||
Resolution string
|
||||
// ImageURL is the optional first-frame image (official "image").
|
||||
ImageURL string
|
||||
// ReferenceURLs are style/content references (official "reference_images").
|
||||
ReferenceURLs []string
|
||||
}
|
||||
|
||||
@@ -54,13 +57,14 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job,
|
||||
if s.mediaJobs == nil || s.mediaQueue == nil {
|
||||
return media.Job{}, fmt.Errorf("视频任务服务未配置")
|
||||
}
|
||||
if len(input.Prompt) > 100000 || (len(input.Prompt) == 0 && len(input.ReferenceURLs) == 0) {
|
||||
if len(input.Prompt) > 100000 || (len(input.Prompt) == 0 && strings.TrimSpace(input.ImageURL) == "" && len(input.ReferenceURLs) == 0) {
|
||||
return media.Job{}, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt")
|
||||
}
|
||||
if err := s.validateVideoInputReferences(ctx, input.ReferenceURLs); err != nil {
|
||||
allRefs := videoInputReferences(input.ImageURL, input.ReferenceURLs)
|
||||
if err := s.validateVideoInputReferences(ctx, allRefs); err != nil {
|
||||
return media.Job{}, err
|
||||
}
|
||||
inputJSON, err := encodeVideoInput(input.ReferenceURLs)
|
||||
inputJSON, err := encodeVideoInput(input.ImageURL, input.ReferenceURLs)
|
||||
if err != nil {
|
||||
return media.Job{}, err
|
||||
}
|
||||
@@ -97,7 +101,7 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job,
|
||||
AccountID: accountID, AccountName: lease.Credential.Name,
|
||||
Provider: string(route.Provider), Model: externalModel, ModelRouteID: route.ID, UpstreamModel: model.DisplayUpstreamModel(route.Provider, route.UpstreamModel), Prompt: input.Prompt,
|
||||
Seconds: input.Duration, Size: input.AspectRatio, Quality: input.Resolution,
|
||||
Status: media.StatusQueued, Progress: 0, InputJSON: inputJSON, InputImageCount: len(input.ReferenceURLs), CreatedAt: now, UpdatedAt: now,
|
||||
Status: media.StatusQueued, Progress: 0, InputJSON: inputJSON, InputImageCount: len(allRefs), CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
reserved := false
|
||||
if pricing, ok := audit.EstimateOfficialVideoCost(externalModel, input.Resolution, input.Duration); ok {
|
||||
@@ -333,7 +337,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
s.failVideoJob(parent, job, "provider_unavailable", ErrNoAvailableAccount)
|
||||
return
|
||||
}
|
||||
referenceURLs, err := s.resolveVideoInputReferences(ctx, inputReferences)
|
||||
imageURL, referenceURLs, err := s.resolveVideoInputParts(ctx, job.InputJSON)
|
||||
if err != nil {
|
||||
s.failVideoJob(parent, job, "input_unavailable", err)
|
||||
return
|
||||
@@ -342,7 +346,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
result, err := adapter.GenerateVideo(ctx, provider.VideoRequest{
|
||||
Credential: lease.Credential, Billing: lease.Billing, JobID: job.ID, Model: route.UpstreamModel,
|
||||
Prompt: job.Prompt, Duration: job.Seconds, AspectRatio: job.Size, Resolution: job.Quality,
|
||||
ReferenceURLs: referenceURLs,
|
||||
ImageURL: imageURL, ReferenceURLs: referenceURLs,
|
||||
Progress: func(value int) {
|
||||
value = min(99, max(1, value))
|
||||
if value-lastProgress < 5 {
|
||||
@@ -499,6 +503,37 @@ func (s *Service) validateVideoInputReferences(ctx context.Context, references [
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) resolveVideoInputParts(ctx context.Context, inputJSON string) (string, []string, error) {
|
||||
imageURL, referenceURLs := decodeVideoInputParts(inputJSON)
|
||||
all := videoInputReferences(imageURL, referenceURLs)
|
||||
resolved, err := s.resolveVideoInputReferences(ctx, all)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
// Map resolved URLs back while preserving empty/non-empty slots by original order.
|
||||
next := 0
|
||||
take := func(original string) string {
|
||||
original = strings.TrimSpace(original)
|
||||
if original == "" {
|
||||
return ""
|
||||
}
|
||||
if next >= len(resolved) {
|
||||
return original
|
||||
}
|
||||
value := resolved[next]
|
||||
next++
|
||||
return value
|
||||
}
|
||||
outImage := take(imageURL)
|
||||
outRefs := make([]string, 0, len(referenceURLs))
|
||||
for _, raw := range referenceURLs {
|
||||
if value := take(raw); value != "" {
|
||||
outRefs = append(outRefs, value)
|
||||
}
|
||||
}
|
||||
return outImage, outRefs, nil
|
||||
}
|
||||
|
||||
func (s *Service) resolveVideoInputReferences(ctx context.Context, references []string) ([]string, error) {
|
||||
resolved := make([]string, 0, len(references))
|
||||
estimatedBytes := videoInputJSONBaseBytes
|
||||
@@ -672,8 +707,27 @@ func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationM
|
||||
return s.mediaJobs.MarkMediaJobUsageRecorded(markCtx, job.ID, time.Now().UTC())
|
||||
}
|
||||
|
||||
func encodeVideoInput(referenceURLs []string) (string, error) {
|
||||
data, err := json.Marshal(map[string][]string{"image_urls": referenceURLs})
|
||||
func encodeVideoInput(imageURL string, referenceURLs []string) (string, error) {
|
||||
payload := map[string]any{}
|
||||
if value := strings.TrimSpace(imageURL); value != "" {
|
||||
payload["image_url"] = value
|
||||
}
|
||||
refs := make([]string, 0, len(referenceURLs))
|
||||
for _, raw := range referenceURLs {
|
||||
if value := strings.TrimSpace(raw); value != "" {
|
||||
refs = append(refs, value)
|
||||
}
|
||||
}
|
||||
if len(refs) > 0 {
|
||||
payload["reference_urls"] = refs
|
||||
}
|
||||
// Keep a combined image_urls field for older readers/tools that only
|
||||
// understand the pre-split shape. New workers prefer image_url/reference_urls.
|
||||
combined := videoInputReferences(imageURL, referenceURLs)
|
||||
if len(combined) > 0 {
|
||||
payload["image_urls"] = combined
|
||||
}
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("编码视频输入: %w", err)
|
||||
}
|
||||
@@ -684,9 +738,55 @@ func encodeVideoInput(referenceURLs []string) (string, error) {
|
||||
}
|
||||
|
||||
func decodeVideoInput(value string) []string {
|
||||
var input map[string][]string
|
||||
imageURL, refs := decodeVideoInputParts(value)
|
||||
return videoInputReferences(imageURL, refs)
|
||||
}
|
||||
|
||||
func decodeVideoInputParts(value string) (string, []string) {
|
||||
var input struct {
|
||||
ImageURL string `json:"image_url"`
|
||||
ReferenceURLs []string `json:"reference_urls"`
|
||||
ImageURLs []string `json:"image_urls"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(value), &input)
|
||||
return input["image_urls"]
|
||||
if strings.TrimSpace(input.ImageURL) != "" || len(input.ReferenceURLs) > 0 {
|
||||
refs := make([]string, 0, len(input.ReferenceURLs))
|
||||
for _, raw := range input.ReferenceURLs {
|
||||
if v := strings.TrimSpace(raw); v != "" {
|
||||
refs = append(refs, v)
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(input.ImageURL), refs
|
||||
}
|
||||
// Legacy jobs stored a flat image_urls list. Preserve historical mapping:
|
||||
// one URL was treated as the first-frame image; multiple URLs were references.
|
||||
legacy := make([]string, 0, len(input.ImageURLs))
|
||||
for _, raw := range input.ImageURLs {
|
||||
if v := strings.TrimSpace(raw); v != "" {
|
||||
legacy = append(legacy, v)
|
||||
}
|
||||
}
|
||||
switch len(legacy) {
|
||||
case 0:
|
||||
return "", nil
|
||||
case 1:
|
||||
return legacy[0], nil
|
||||
default:
|
||||
return "", legacy
|
||||
}
|
||||
}
|
||||
|
||||
func videoInputReferences(imageURL string, referenceURLs []string) []string {
|
||||
values := make([]string, 0, 1+len(referenceURLs))
|
||||
if v := strings.TrimSpace(imageURL); v != "" {
|
||||
values = append(values, v)
|
||||
}
|
||||
for _, raw := range referenceURLs {
|
||||
if v := strings.TrimSpace(raw); v != "" {
|
||||
values = append(values, v)
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func (s *Service) failVideoJob(ctx context.Context, job media.Job, code string, err error) {
|
||||
|
||||
@@ -48,17 +48,52 @@ func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestEncodeVideoInputEnforcesPersistedLimit(t *testing.T) {
|
||||
overhead := len(`{"image_urls":[""]}`)
|
||||
atLimit := strings.Repeat("A", media.MaxInputJSONBytes-overhead)
|
||||
encoded, err := encodeVideoInput([]string{atLimit})
|
||||
if err != nil || len(encoded) != media.MaxInputJSONBytes {
|
||||
t.Fatalf("encoded len=%d err=%v", len(encoded), err)
|
||||
// image_url and combined image_urls both store the same value, so the URL is counted twice.
|
||||
base := `{"image_url":"","image_urls":[""]}`
|
||||
overhead := len(base)
|
||||
urlLen := (media.MaxInputJSONBytes - overhead) / 2
|
||||
atLimit := strings.Repeat("A", urlLen)
|
||||
encoded, err := encodeVideoInput(atLimit, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("encode at limit: %v", err)
|
||||
}
|
||||
if _, err := encodeVideoInput([]string{atLimit + "A"}); !errors.Is(err, ErrVideoInputTooLarge) {
|
||||
if len(encoded) > media.MaxInputJSONBytes {
|
||||
t.Fatalf("encoded len=%d exceeds limit", len(encoded))
|
||||
}
|
||||
if _, err := encodeVideoInput(atLimit+"AA", nil); !errors.Is(err, ErrVideoInputTooLarge) {
|
||||
t.Fatalf("oversized input error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeDecodeVideoInputPreservesImageAndReferences(t *testing.T) {
|
||||
encoded, err := encodeVideoInput("https://example.com/first.png", []string{"https://example.com/ref.png"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
imageURL, refs := decodeVideoInputParts(encoded)
|
||||
if imageURL != "https://example.com/first.png" || len(refs) != 1 || refs[0] != "https://example.com/ref.png" {
|
||||
t.Fatalf("decoded split = %q %#v from %s", imageURL, refs, encoded)
|
||||
}
|
||||
|
||||
encoded, err = encodeVideoInput("", []string{"https://example.com/ref-only.png"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
imageURL, refs = decodeVideoInputParts(encoded)
|
||||
if imageURL != "" || len(refs) != 1 || refs[0] != "https://example.com/ref-only.png" {
|
||||
t.Fatalf("single reference decoded = %q %#v from %s", imageURL, refs, encoded)
|
||||
}
|
||||
|
||||
imageURL, refs = decodeVideoInputParts(`{"image_urls":["https://legacy/one.png"]}`)
|
||||
if imageURL != "https://legacy/one.png" || len(refs) != 0 {
|
||||
t.Fatalf("legacy single = %q %#v", imageURL, refs)
|
||||
}
|
||||
imageURL, refs = decodeVideoInputParts(`{"image_urls":["https://legacy/a.png","https://legacy/b.png"]}`)
|
||||
if imageURL != "" || len(refs) != 2 || refs[0] != "https://legacy/a.png" || refs[1] != "https://legacy/b.png" {
|
||||
t.Fatalf("legacy multi = %q %#v", imageURL, refs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverVideoJobsRecordsFailedAuditWithEgress(t *testing.T) {
|
||||
completedAt := time.Now().UTC()
|
||||
nodeID := uint64(42)
|
||||
|
||||
@@ -669,7 +669,7 @@ func TestGenerateVideoFallbackInjectsUploadURL(t *testing.T) {
|
||||
})
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: account.Credential{ID: 15, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted, BuildSuperEntitled: true},
|
||||
JobID: "video_job_1", Prompt: "waves", Duration: 6, Resolution: "720p", ReferenceURLs: []string{"https://cdn.example.com/first.png"},
|
||||
JobID: "video_job_1", Prompt: "waves", Duration: 6, Resolution: "720p", ImageURL: "https://cdn.example.com/first.png",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -750,7 +750,7 @@ func TestGenerateVideoAutoBotFlaggedUsesXAIDirectly(t *testing.T) {
|
||||
})
|
||||
result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: account.Credential{ID: 116, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted, BuildRouteMode: account.BuildRouteAuto, BuildSuperEntitled: true},
|
||||
JobID: "video_bot", Prompt: "waves", Duration: 6, Resolution: "720p", ReferenceURLs: []string{"https://cdn.example.com/bot.png"},
|
||||
JobID: "video_bot", Prompt: "waves", Duration: 6, Resolution: "720p", ImageURL: "https://cdn.example.com/bot.png",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -23,7 +23,7 @@ const (
|
||||
buildVideoModel = "grok-imagine-video-1.5"
|
||||
xaiVideoModel = "grok-imagine-video-1.5-preview"
|
||||
// Align with the gateway ceiling and official xAI video inputs:
|
||||
// one start frame via image, or multiple references via reference_images.
|
||||
// image = first frame; reference_images = style/content references (may be length 1).
|
||||
buildVideoMaxImages = mediadomain.MaxInputImages
|
||||
buildVideoPollEvery = 2 * time.Second
|
||||
buildVideoMaxBodySize = 2 << 20
|
||||
@@ -152,12 +152,12 @@ func boundDiagnosticText(value string, limit int) string {
|
||||
|
||||
// GenerateVideo 通过 Build OAuth 创建并轮询视频任务;对外仍使用 grok-imagine-video-1.5,
|
||||
// 发往 XAI 时仅在出站协议层转换为官方 preview 模型与 image/reference_images 结构。
|
||||
// 1 张图映射为 image;多张图映射为 reference_images。超过网关上限时失败,不静默截断。
|
||||
// image = 首帧;reference_images = 参考图(即使只有 1 张也不升格为 image)。超过网关上限时失败,不静默截断。
|
||||
// 显式模式优先;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 最多支持 %d 张参考图,当前为 %d 张", buildVideoMaxImages, len(request.ReferenceURLs))
|
||||
if total := buildVideoImageCount(request); total > buildVideoMaxImages {
|
||||
return provider.VideoResult{}, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 %d 张输入图,当前为 %d 张", buildVideoMaxImages, total)
|
||||
}
|
||||
accessToken, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken)
|
||||
if err != nil {
|
||||
@@ -294,24 +294,19 @@ func videoCreatePayload(request provider.VideoRequest, uploadURL string, profile
|
||||
if resolution := strings.TrimSpace(request.Resolution); resolution != "" {
|
||||
payload["resolution"] = resolution
|
||||
}
|
||||
switch len(request.ReferenceURLs) {
|
||||
case 0:
|
||||
// text-to-video
|
||||
case 1:
|
||||
imageURL := strings.TrimSpace(request.ReferenceURLs[0])
|
||||
if imageURL == "" {
|
||||
return nil, fmt.Errorf("视频首图 URL 不能为空")
|
||||
}
|
||||
if imageURL := strings.TrimSpace(request.ImageURL); imageURL != "" {
|
||||
payload["image"] = map[string]any{profile.imageURLField: imageURL}
|
||||
default:
|
||||
}
|
||||
if len(request.ReferenceURLs) > 0 {
|
||||
references := make([]map[string]any, 0, len(request.ReferenceURLs))
|
||||
for _, rawURL := range request.ReferenceURLs {
|
||||
imageURL := strings.TrimSpace(rawURL)
|
||||
if imageURL == "" {
|
||||
refURL := strings.TrimSpace(rawURL)
|
||||
if refURL == "" {
|
||||
return nil, fmt.Errorf("视频参考图 URL 不能为空")
|
||||
}
|
||||
references = append(references, map[string]any{profile.imageURLField: imageURL})
|
||||
references = append(references, map[string]any{profile.imageURLField: refURL})
|
||||
}
|
||||
// A single reference must stay in reference_images; do not coerce to image.
|
||||
payload["reference_images"] = references
|
||||
}
|
||||
if _, hasPrompt := payload["prompt"]; !hasPrompt {
|
||||
@@ -573,3 +568,16 @@ func numberAsInt(value any) (int, bool) {
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func buildVideoImageCount(request provider.VideoRequest) int {
|
||||
count := 0
|
||||
if strings.TrimSpace(request.ImageURL) != "" {
|
||||
count++
|
||||
}
|
||||
for _, raw := range request.ReferenceURLs {
|
||||
if strings.TrimSpace(raw) != "" {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -38,7 +38,7 @@ func TestBuildVideoCreatePayloadNoImageAndSingleR2URL(t *testing.T) {
|
||||
|
||||
withImage, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://cdn.example.com/r2/first.png"},
|
||||
ImageURL: "https://cdn.example.com/r2/first.png",
|
||||
}, "", buildVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -47,10 +47,28 @@ func TestBuildVideoCreatePayloadNoImageAndSingleR2URL(t *testing.T) {
|
||||
if !ok || image["image_url"] != "https://cdn.example.com/r2/first.png" {
|
||||
t.Fatalf("image payload = %#v", withImage)
|
||||
}
|
||||
if _, exists := withImage["reference_images"]; exists {
|
||||
t.Fatalf("first-frame payload must not include reference_images: %#v", withImage)
|
||||
}
|
||||
if withImage["model"] != buildVideoModel || withImage["resolution"] != "720p" || withImage["aspect_ratio"] != "16:9" {
|
||||
t.Fatalf("single-image payload = %#v", withImage)
|
||||
}
|
||||
|
||||
withSingleReference, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://cdn.example.com/r2/ref-only.png"},
|
||||
}, "", buildVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, exists := withSingleReference["image"]; exists {
|
||||
t.Fatalf("single reference must not coerce to image: %#v", withSingleReference)
|
||||
}
|
||||
singleRefs, ok := withSingleReference["reference_images"].([]map[string]any)
|
||||
if !ok || len(singleRefs) != 1 || singleRefs[0]["image_url"] != "https://cdn.example.com/r2/ref-only.png" {
|
||||
t.Fatalf("single reference payload = %#v", withSingleReference)
|
||||
}
|
||||
|
||||
withUpload, err := videoCreatePayload(provider.VideoRequest{Prompt: "x", Duration: 6}, "https://api.example/v1/media/uploads/tok", buildVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -63,11 +81,11 @@ func TestBuildVideoCreatePayloadNoImageAndSingleR2URL(t *testing.T) {
|
||||
|
||||
func TestBuildVideoCreatePayloadImageOnlyEmptyPrompt(t *testing.T) {
|
||||
payload, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: " ",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://r2.example.com/first.png"},
|
||||
Prompt: " ",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ImageURL: "https://r2.example.com/first.png",
|
||||
}, "", buildVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -83,11 +101,11 @@ func TestBuildVideoCreatePayloadImageOnlyEmptyPrompt(t *testing.T) {
|
||||
|
||||
func TestXAIVideoCreatePayloadMatchesOfficialSchema(t *testing.T) {
|
||||
payload, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: "animate",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ReferenceURLs: []string{"https://cdn.example.com/r2/first.png"},
|
||||
Prompt: "animate",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ImageURL: "https://cdn.example.com/r2/first.png",
|
||||
}, "https://api.example/v1/media/uploads/tok", xaiVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -153,6 +171,28 @@ func TestBuildVideoCreatePayloadMapsMultipleReferences(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildVideoCreatePayloadKeepsImageAndReferences(t *testing.T) {
|
||||
payload, err := videoCreatePayload(provider.VideoRequest{
|
||||
Prompt: "animate",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ImageURL: "https://cdn.example.com/first-frame.png",
|
||||
ReferenceURLs: []string{"https://cdn.example.com/ref.png"},
|
||||
}, "", buildVideoRequestProfile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
image, ok := payload["image"].(map[string]any)
|
||||
if !ok || image["image_url"] != "https://cdn.example.com/first-frame.png" {
|
||||
t.Fatalf("image = %#v", payload["image"])
|
||||
}
|
||||
references, ok := payload["reference_images"].([]map[string]any)
|
||||
if !ok || len(references) != 1 || references[0]["image_url"] != "https://cdn.example.com/ref.png" {
|
||||
t.Fatalf("reference_images = %#v", payload["reference_images"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateVideoRejectsTooManyImagesBeforeUpstream(t *testing.T) {
|
||||
adapter, encrypted := newTestBuildVideoAdapter(t)
|
||||
var hits atomic.Int32
|
||||
@@ -275,12 +315,12 @@ func TestGenerateVideoPostsSingleImageAndPollsUntilReady(t *testing.T) {
|
||||
|
||||
var progressValues []int
|
||||
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"},
|
||||
Credential: account.Credential{ID: 9, UserID: "user-1", EncryptedAccessToken: encrypted},
|
||||
Prompt: "animate knife",
|
||||
Duration: 6,
|
||||
AspectRatio: "16:9",
|
||||
Resolution: "720p",
|
||||
ImageURL: "https://r2.example.com/first.png",
|
||||
Progress: func(value int) {
|
||||
progressValues = append(progressValues, value)
|
||||
},
|
||||
|
||||
@@ -1326,6 +1326,100 @@ func TestConsoleVideoPostsReferenceImages(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoPostsSingleReferenceImage(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("single reference must not coerce to image: %#v", payload)
|
||||
}
|
||||
references, ok := payload["reference_images"].([]any)
|
||||
if !ok || len(references) != 1 {
|
||||
t.Errorf("reference_images = %#v", payload["reference_images"])
|
||||
} else {
|
||||
first, _ := references[0].(map[string]any)
|
||||
if first["url"] != "https://example.com/ref-only.png" {
|
||||
t.Errorf("reference_images = %#v", references)
|
||||
}
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"request_id":"upstream-video-ref-single"}`))
|
||||
case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-ref-single":
|
||||
_, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-ref-single.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/ref-only.png"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.URL != "https://vidgen.x.ai/result-ref-single.mp4" {
|
||||
t.Fatalf("video result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoPostsFirstFrameAndReferences(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)
|
||||
}
|
||||
image, ok := payload["image"].(map[string]any)
|
||||
if !ok || image["url"] != "https://example.com/first.png" {
|
||||
t.Errorf("image = %#v", payload["image"])
|
||||
}
|
||||
references, ok := payload["reference_images"].([]any)
|
||||
if !ok || len(references) != 1 {
|
||||
t.Errorf("reference_images = %#v", payload["reference_images"])
|
||||
} else {
|
||||
first, _ := references[0].(map[string]any)
|
||||
if first["url"] != "https://example.com/ref.png" {
|
||||
t.Errorf("reference_images = %#v", references)
|
||||
}
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"request_id":"upstream-video-both"}`))
|
||||
case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-both":
|
||||
_, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-both.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",
|
||||
ImageURL: "https://example.com/first.png",
|
||||
ReferenceURLs: []string{"https://example.com/ref.png"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.URL != "https://vidgen.x.ai/result-both.mp4" {
|
||||
t.Fatalf("video result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) {
|
||||
adapter, credential := newConsoleTestAdapter(t, "https://console.example")
|
||||
references := make([]string, consoleMaxVideoImages+1)
|
||||
@@ -1340,6 +1434,21 @@ func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoRejectsTooManyCombinedImages(t *testing.T) {
|
||||
adapter, credential := newConsoleTestAdapter(t, "https://console.example")
|
||||
references := make([]string, consoleMaxVideoImages)
|
||||
for i := range references {
|
||||
references[i] = "https://example.com/" + strings.Repeat("y", i+1) + ".png"
|
||||
}
|
||||
_, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{
|
||||
Credential: credential, Prompt: "animate", Duration: 6,
|
||||
ImageURL: "https://example.com/first.png", ReferenceURLs: references,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "最多支持") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleVideoUsesImagineVideo15Model(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if serveTestDPoPToken(t, writer, request) {
|
||||
|
||||
@@ -30,7 +30,7 @@ const (
|
||||
consoleVideoPollEvery = 2 * time.Second
|
||||
consoleMaxEditImages = 3
|
||||
// Align with the gateway ceiling and official xAI video inputs:
|
||||
// one start frame via image, or multiple references via reference_images.
|
||||
// image = first frame; reference_images = style/content references (may be length 1).
|
||||
consoleMaxVideoImages = mediadomain.MaxInputImages
|
||||
)
|
||||
|
||||
@@ -403,8 +403,9 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque
|
||||
if !ResolveMedia(modelName, modeldomain.CapabilityVideo) {
|
||||
return provider.VideoResult{}, fmt.Errorf("Console 视频模型未注册: %s", modelName)
|
||||
}
|
||||
if len(request.ReferenceURLs) > consoleMaxVideoImages {
|
||||
return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张参考图,当前为 %d 张", modelName, consoleMaxVideoImages, len(request.ReferenceURLs))
|
||||
totalImages := consoleVideoImageCount(request)
|
||||
if totalImages > consoleMaxVideoImages {
|
||||
return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张输入图,当前为 %d 张", modelName, consoleMaxVideoImages, totalImages)
|
||||
}
|
||||
if request.Duration < 1 || request.Duration > 15 {
|
||||
return provider.VideoResult{}, errors.New("duration 必须在 1 到 15 秒之间")
|
||||
@@ -424,16 +425,13 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque
|
||||
if resolution := strings.TrimSpace(request.Resolution); resolution != "" {
|
||||
payload["resolution"] = resolution
|
||||
}
|
||||
switch len(request.ReferenceURLs) {
|
||||
case 0:
|
||||
// text-to-video
|
||||
case 1:
|
||||
value := strings.TrimSpace(request.ReferenceURLs[0])
|
||||
if !validConsoleMediaInputURL(value, "image") {
|
||||
if imageURL := strings.TrimSpace(request.ImageURL); imageURL != "" {
|
||||
if !validConsoleMediaInputURL(imageURL, "image") {
|
||||
return provider.VideoResult{}, errors.New("视频首图必须是 HTTPS URL 或 image data URL")
|
||||
}
|
||||
payload["image"] = map[string]any{"url": value}
|
||||
default:
|
||||
payload["image"] = map[string]any{"url": imageURL}
|
||||
}
|
||||
if len(request.ReferenceURLs) > 0 {
|
||||
references := make([]map[string]any, 0, len(request.ReferenceURLs))
|
||||
for _, rawURL := range request.ReferenceURLs {
|
||||
value := strings.TrimSpace(rawURL)
|
||||
@@ -442,6 +440,7 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque
|
||||
}
|
||||
references = append(references, map[string]any{"url": value})
|
||||
}
|
||||
// A single reference must stay in reference_images; do not coerce to image.
|
||||
payload["reference_images"] = references
|
||||
}
|
||||
if _, hasPrompt := payload["prompt"]; !hasPrompt {
|
||||
@@ -752,3 +751,16 @@ func trustedConsoleVideoHost(host string) bool {
|
||||
host = strings.ToLower(strings.TrimSpace(host))
|
||||
return host == "vidgen.x.ai" || strings.HasSuffix(host, ".vidgen.x.ai")
|
||||
}
|
||||
|
||||
func consoleVideoImageCount(request provider.VideoRequest) int {
|
||||
count := 0
|
||||
if strings.TrimSpace(request.ImageURL) != "" {
|
||||
count++
|
||||
}
|
||||
for _, raw := range request.ReferenceURLs {
|
||||
if strings.TrimSpace(raw) != "" {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -280,11 +280,15 @@ type VideoRequest struct {
|
||||
// JobID binds the local video job to XAI ZDR upload tickets and result assets.
|
||||
JobID string
|
||||
// Model is the selected upstream video model when the Provider supports more than one.
|
||||
Model string
|
||||
Model string
|
||||
Prompt string
|
||||
Duration int
|
||||
AspectRatio string
|
||||
Resolution string
|
||||
// ImageURL is the optional first-frame image (official "image" field).
|
||||
ImageURL string
|
||||
// ReferenceURLs are style/content references (official "reference_images").
|
||||
// A single reference must stay in reference_images and must not be coerced to image.
|
||||
ReferenceURLs []string
|
||||
Progress func(int)
|
||||
}
|
||||
|
||||
@@ -219,8 +219,17 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque
|
||||
}
|
||||
defer lease.Release()
|
||||
parentID := ""
|
||||
references := make([]string, 0, len(request.ReferenceURLs))
|
||||
rawReferences := make([]string, 0, 1+len(request.ReferenceURLs))
|
||||
if imageURL := strings.TrimSpace(request.ImageURL); imageURL != "" {
|
||||
rawReferences = append(rawReferences, imageURL)
|
||||
}
|
||||
for _, rawReference := range request.ReferenceURLs {
|
||||
if value := strings.TrimSpace(rawReference); value != "" {
|
||||
rawReferences = append(rawReferences, value)
|
||||
}
|
||||
}
|
||||
references := make([]string, 0, len(rawReferences))
|
||||
for _, rawReference := range rawReferences {
|
||||
reference, referenceErr := a.prepareVideoReference(ctx, cfg, lease, token, rawReference)
|
||||
if referenceErr != nil {
|
||||
return provider.VideoResult{}, referenceErr
|
||||
|
||||
@@ -666,33 +666,47 @@ func (h *Handler) generateVideo(c *gin.Context) {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "resolution 必须是 480p、720p 或 1080p")
|
||||
return
|
||||
}
|
||||
inputs := append([]videoGenerationImage(nil), request.ReferenceImages...)
|
||||
if request.Image != nil {
|
||||
inputs = append([]videoGenerationImage{*request.Image}, inputs...)
|
||||
}
|
||||
if len(inputs) > mediadomain.MaxInputImages {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", fmt.Sprintf("image 与 reference_images 合计不能超过 %d 张", mediadomain.MaxInputImages))
|
||||
return
|
||||
}
|
||||
referenceURLs := make([]string, 0, len(inputs))
|
||||
for _, input := range inputs {
|
||||
parseVideoImage := func(input videoGenerationImage, field string) (string, bool) {
|
||||
urlValue := strings.TrimSpace(input.URL)
|
||||
fileID := strings.TrimSpace(input.FileID)
|
||||
if (urlValue == "") == (fileID == "") {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "每个 image 必须且只能提供 url 或 file_id")
|
||||
return
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", field+" 必须且只能提供 url 或 file_id")
|
||||
return "", false
|
||||
}
|
||||
if fileID != "" {
|
||||
if !mediadomain.IsInputAssetID(fileID) {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "image.file_id 无效")
|
||||
return
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", field+".file_id 无效")
|
||||
return "", false
|
||||
}
|
||||
referenceURLs = append(referenceURLs, gateway.VideoInputFileReference(fileID))
|
||||
} else {
|
||||
referenceURLs = append(referenceURLs, urlValue)
|
||||
return gateway.VideoInputFileReference(fileID), true
|
||||
}
|
||||
return urlValue, true
|
||||
}
|
||||
if prompt == "" && len(referenceURLs) == 0 {
|
||||
imageURL := ""
|
||||
if request.Image != nil {
|
||||
value, ok := parseVideoImage(*request.Image, "image")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
imageURL = value
|
||||
}
|
||||
referenceURLs := make([]string, 0, len(request.ReferenceImages))
|
||||
for _, input := range request.ReferenceImages {
|
||||
value, ok := parseVideoImage(input, "reference_images")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
referenceURLs = append(referenceURLs, value)
|
||||
}
|
||||
totalImages := len(referenceURLs)
|
||||
if imageURL != "" {
|
||||
totalImages++
|
||||
}
|
||||
if totalImages > mediadomain.MaxInputImages {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", fmt.Sprintf("image 与 reference_images 合计不能超过 %d 张", mediadomain.MaxInputImages))
|
||||
return
|
||||
}
|
||||
if prompt == "" && imageURL == "" && len(referenceURLs) == 0 {
|
||||
writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "文本生视频必须提供 prompt;图片生视频可以省略 prompt")
|
||||
return
|
||||
}
|
||||
@@ -703,7 +717,7 @@ func (h *Handler) generateVideo(c *gin.Context) {
|
||||
job, err := h.gateway.CreateVideo(c.Request.Context(), gateway.VideoInput{
|
||||
RequestID: requestID, ClientKey: clientKey, PublicModel: model,
|
||||
Prompt: prompt, Duration: duration, AspectRatio: aspectRatio, Resolution: resolution,
|
||||
ReferenceURLs: referenceURLs,
|
||||
ImageURL: imageURL, ReferenceURLs: referenceURLs,
|
||||
})
|
||||
if err != nil {
|
||||
writeGatewayError(c, err)
|
||||
|
||||
Reference in new issue
Block a user