diff --git a/sdk/api/handlers/openai/openai_videos_handlers.go b/sdk/api/handlers/openai/openai_videos_handlers.go index 673f2a9838..3e7f8aa8e9 100644 --- a/sdk/api/handlers/openai/openai_videos_handlers.go +++ b/sdk/api/handlers/openai/openai_videos_handlers.go @@ -280,16 +280,101 @@ func videosCreateRequestFromForm(c *gin.Context) ([]byte, error) { if value := strings.TrimSpace(firstPostForm(c, "input_reference[file_id]", "input_reference.file_id", "file_id")); value != "" { _ = rawDoc.Set("input_reference.file_id", value) } - if refs := strings.TrimSpace(c.PostForm("reference_image_urls")); refs != "" { - for _, ref := range strings.Split(refs, ",") { - if ref = strings.TrimSpace(ref); ref != "" { - _ = rawDoc.Set("reference_image_urls.-1", ref) - } + refValues := append([]string(nil), c.PostFormArray("reference_image_urls")...) + refValues = append(refValues, c.PostFormArray("reference_image_urls[]")...) + for _, rawRef := range refValues { + for _, ref := range parseReferenceImageURLFormValue(rawRef) { + _ = rawDoc.Set("reference_image_urls.-1", ref) } } return rawDoc.Bytes(), nil } +func parseReferenceImageURLFormValue(raw string) []string { + trimmed := strings.TrimSpace(raw) + if trimmed == "" { + return nil + } + if strings.HasPrefix(trimmed, "[") && ojson.Valid(trimmed) { + parsed := ojson.Parse(trimmed) + if parsed.IsArray() { + var out []string + parsed.ForEach(func(_, item ojson.Result) bool { + var value string + switch { + case item.Type == ojson.String: + value = strings.TrimSpace(item.String()) + case item.IsObject(): + if directURL := item.Get("url"); directURL.Type == ojson.String { + value = strings.TrimSpace(directURL.String()) + } + if value == "" { + if nestedURL := item.Get("image_url.url"); nestedURL.Type == ojson.String { + value = strings.TrimSpace(nestedURL.String()) + } + } + } + if value != "" { + out = append(out, value) + } + return true + }) + return out + } + } + + parts := strings.Split(trimmed, ",") + out := make([]string, 0, len(parts)) + for i := 0; i < len(parts); i++ { + part := strings.TrimSpace(parts[i]) + if part == "" { + continue + } + if isReferenceURLBoundary(part) { + var b strings.Builder + b.WriteString(part) + if hasDataURLPrefix(part) && i+1 < len(parts) { + b.WriteByte(',') + b.WriteString(strings.TrimLeft(parts[i+1], " \t\r\n")) + i++ + } + for i+1 < len(parts) { + nextIdx := i + 1 + for nextIdx < len(parts) && strings.TrimSpace(parts[nextIdx]) == "" { + nextIdx++ + } + if nextIdx >= len(parts) { + i = len(parts) - 1 + break + } + if isReferenceURLBoundary(strings.TrimSpace(parts[nextIdx])) { + i = nextIdx - 1 + break + } + for j := i + 1; j <= nextIdx; j++ { + b.WriteByte(',') + b.WriteString(parts[j]) + } + i = nextIdx + } + out = append(out, strings.TrimSpace(b.String())) + continue + } + out = append(out, part) + } + return out +} + +func hasDataURLPrefix(value string) bool { + return len(value) >= len("data:") && strings.EqualFold(value[:len("data:")], "data:") +} + +func isReferenceURLBoundary(value string) bool { + return hasDataURLPrefix(value) || + (len(value) >= len("http://") && strings.EqualFold(value[:len("http://")], "http://")) || + (len(value) >= len("https://") && strings.EqualFold(value[:len("https://")], "https://")) +} + func firstPostForm(c *gin.Context, keys ...string) string { for _, key := range keys { if value := c.PostForm(key); strings.TrimSpace(value) != "" { diff --git a/sdk/api/handlers/openai/openai_videos_handlers_test.go b/sdk/api/handlers/openai/openai_videos_handlers_test.go index c23895381b..805c056811 100644 --- a/sdk/api/handlers/openai/openai_videos_handlers_test.go +++ b/sdk/api/handlers/openai/openai_videos_handlers_test.go @@ -1,10 +1,14 @@ package openai import ( + "bytes" "context" "io" + "mime/multipart" "net/http" "net/http/httptest" + "net/url" + "reflect" "strconv" "strings" "sync" @@ -1227,3 +1231,251 @@ func videosCreateRequestFromFormContext(body string) ([]byte, error) { router.ServeHTTP(resp, req) return rawJSON, err } + +type formFieldPair struct { + key string + value string +} + +func videosCreateRequestFromMultipartContext(t *testing.T, fields []formFieldPair) ([]byte, error) { + t.Helper() + + var body bytes.Buffer + writer := multipart.NewWriter(&body) + for _, field := range fields { + if errWrite := writer.WriteField(field.key, field.value); errWrite != nil { + t.Fatalf("WriteField(%q) error = %v", field.key, errWrite) + } + } + if errClose := writer.Close(); errClose != nil { + t.Fatalf("multipart writer Close() error = %v", errClose) + } + + gin.SetMode(gin.TestMode) + router := gin.New() + var rawJSON []byte + var err error + router.POST(videosPath, func(c *gin.Context) { + rawJSON, err = videosCreateRequestFromForm(c) + }) + req := httptest.NewRequest(http.MethodPost, videosPath, &body) + req.Header.Set("Content-Type", writer.FormDataContentType()) + resp := httptest.NewRecorder() + router.ServeHTTP(resp, req) + return rawJSON, err +} + +func TestVideosCreateFormRequestReferenceImageURLs(t *testing.T) { + const ( + dataURLPNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB" + dataURLJPEG = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/" + dataURLSVG = "data:image/svg+xml,a,b" + httpsURLA = "https://example.com/a.png" + httpsURLB = "https://example.com/b.png" + ) + + tests := []struct { + name string + multipart bool + fields []formFieldPair + want []string + }{ + { + name: "multipart single base64 data URL", + multipart: true, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: dataURLPNG}, + }, + want: []string{dataURLPNG}, + }, + { + name: "multipart repeated reference_image_urls fields", + multipart: true, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: httpsURLA}, + {key: "reference_image_urls", value: httpsURLB}, + }, + want: []string{httpsURLA, httpsURLB}, + }, + { + name: "multipart bracketed reference_image_urls[] fields with data URL", + multipart: true, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls[]", value: httpsURLA}, + {key: "reference_image_urls[]", value: dataURLPNG}, + }, + want: []string{httpsURLA, dataURLPNG}, + }, + { + name: "urlencoded repeated and bracketed fields", + multipart: false, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: httpsURLA}, + {key: "reference_image_urls", value: dataURLPNG}, + {key: "reference_image_urls[]", value: httpsURLB}, + }, + want: []string{httpsURLA, dataURLPNG, httpsURLB}, + }, + { + name: "multipart JSON array containing https and data URL", + multipart: true, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: `["` + httpsURLA + `","` + dataURLPNG + `"]`}, + }, + want: []string{httpsURLA, dataURLPNG}, + }, + { + name: "urlencoded comma-separated https URLs", + multipart: false, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: httpsURLA + ", " + httpsURLB}, + }, + want: []string{httpsURLA, httpsURLB}, + }, + { + name: "urlencoded comma-separated data URL followed by https URL", + multipart: false, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: dataURLPNG + "," + httpsURLB}, + }, + want: []string{dataURLPNG, httpsURLB}, + }, + { + name: "urlencoded comma-separated https URL followed by data URL", + multipart: false, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: httpsURLA + "," + dataURLPNG}, + }, + want: []string{httpsURLA, dataURLPNG}, + }, + { + name: "urlencoded comma-separated multiple data URLs", + multipart: false, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: dataURLPNG + "," + dataURLJPEG}, + }, + want: []string{dataURLPNG, dataURLJPEG}, + }, + { + name: "multipart single data URL with comma in payload", + multipart: true, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: dataURLSVG}, + }, + want: []string{dataURLSVG}, + }, + { + name: "multipart JSON array ignores non-string entries and extracts object URLs", + multipart: true, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: `["https://example.com/a.png", null, 123, {"url":"` + dataURLPNG + `"}, {"image_url":{"url":"https://example.com/b.png"}}]`}, + }, + want: []string{httpsURLA, dataURLPNG, httpsURLB}, + }, + { + name: "urlencoded comma-separated CDN URL with embedded comma", + multipart: false, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: "https://cdn.example.com/cdn-cgi/image/w=800,q=80/a.png," + httpsURLB}, + }, + want: []string{"https://cdn.example.com/cdn-cgi/image/w=800,q=80/a.png", httpsURLB}, + }, + { + name: "multipart single URL containing consecutive commas stays intact", + multipart: true, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: "https://cdn.example/a,,b.png"}, + }, + want: []string{"https://cdn.example/a,,b.png"}, + }, + { + name: "multipart data URL containing consecutive commas stays intact", + multipart: true, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: "data:image/svg+xml,a,,b"}, + }, + want: []string{"data:image/svg+xml,a,,b"}, + }, + { + name: "urlencoded consecutive commas between two URLs split at next URL boundary", + multipart: false, + fields: []formFieldPair{ + {key: "model", value: "grok-imagine-video"}, + {key: "prompt", value: "Animate this scene"}, + {key: "reference_image_urls", value: httpsURLA + ",," + httpsURLB + ","}, + }, + want: []string{httpsURLA, httpsURLB}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var ( + rawJSON []byte + err error + ) + if tc.multipart { + rawJSON, err = videosCreateRequestFromMultipartContext(t, tc.fields) + } else { + form := url.Values{} + for _, field := range tc.fields { + form.Add(field.key, field.value) + } + rawJSON, err = videosCreateRequestFromFormContext(form.Encode()) + } + if err != nil { + t.Fatalf("videosCreateRequestFromForm() error = %v", err) + } + + var got []string + ojson.GetBytesNoCopy(rawJSON, "reference_image_urls").ForEach(func(_, item ojson.Result) bool { + got = append(got, item.String()) + return true + }) + if !reflect.DeepEqual(got, tc.want) { + t.Fatalf("reference_image_urls = %#v, want %#v (raw=%s)", got, tc.want, string(rawJSON)) + } + + xaiPayload, _, errBuild := buildXAIVideosCreateRequest(rawJSON, "grok-imagine-video") + if errBuild != nil { + t.Fatalf("buildXAIVideosCreateRequest() error = %v", errBuild) + } + var gotUpstream []string + ojson.GetBytesNoCopy(xaiPayload, "reference_images").ForEach(func(_, item ojson.Result) bool { + gotUpstream = append(gotUpstream, item.Get("url").String()) + return true + }) + if !reflect.DeepEqual(gotUpstream, tc.want) { + t.Fatalf("upstream reference_images = %#v, want %#v", gotUpstream, tc.want) + } + }) + } +}