diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 4eff964a8..58fba5cb3 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -637,6 +637,25 @@ on the key that started the video. A gateway key's account and model holds apply to all three routes (`videoAsker`, `videoModelHeld`), and to Grok's and Volcengine's polls and downloads as well. +Volcengine Ark has no OpenAI-shaped videos API, so no Ark key is asked at +`/videos` (`filmsOpenAI` is false for `isArk`). Its Seedance models go +to Ark's asynchronous content-generation tasks (`arkFilms`, `arkTasks`: +`POST /contents/generations/tasks`, polled at `GET …/tasks/`, +https://www.volcengine.com/docs/82379/1520757): the preset's Agent Plan's +(`PlanVideos`), and any other Ark key's (pay-as-you-go `/api/v3`, or an Ark +endpoint added by hand) whose list or picked models name `seedance` +(`arkVideoModel`, added in `customVideomakers`; axelburks on Discord). Such a +key's video id ends with the key's fingerprint, as a plan key's does, and +its poll and download go on that key (`videoAsker` checks the calling key +may use it). `volcengineVideoBody` turns OpenAI's request into Ark's: the +prompt as a `text` item in `content`, `input_reference` as an `image_url` +item with role `first_frame`, `reference_images` as `reference_image`, +`seconds` as `duration`, and `size` (WIDTHxHEIGHT) as `ratio` and +`resolution`. Ark's `succeeded`/`running`/`failed`/`expired` and its +`content.video_url` are read back into OpenAI's video object +(`videoObject`), and `/content` fetches that URL (`vendorClient`). +`TestArkKeyMakesSeedanceVideos`. + A MiniMax API key (no account, a Chat, Anthropic or Responses base on api.minimax.io, api.minimaxi.com or api.minimax.cn: `filmsMiniMax`, `minimaxHost`; a relay serving MiniMax's models is not one) makes videos diff --git a/internal/gateway/video.go b/internal/gateway/video.go index 41d2ae6c2..7b7aa4341 100644 --- a/internal/gateway/video.go +++ b/internal/gateway/video.go @@ -120,6 +120,22 @@ func customVideomakers(p provider.Provider) []catalog.Model { for i := range out { out[i].Provider = p.ID } + if isArk(p) { + // a Volcengine Ark key's Seedance models (pay-as-you-go, or one + // added by hand), those its list has and those the user picked, as + // Drawers takes a Seedream: its list marks no kind, and Ark makes + // them at its own content-generation tasks (arkFilms) + ms := p.Available() + for _, id := range p.Models { + ms = append(ms, catalog.Model{ID: id, Name: id}) + } + for _, m := range ms { + if arkVideoModel(m.ID) && !slices.ContainsFunc(out, func(o catalog.Model) bool { return o.ID == m.ID }) { + m.Provider, m.Films = p.ID, true + out = append(out, m) + } + } + } // those the user said make videos, whatever the list says, and none // they said draws (shen-joe, #1399: a relay whose /models marks none) for _, id := range p.KindModels(provider.KindVideo) { @@ -138,12 +154,41 @@ func videoBase(p provider.Provider) string { return strings.TrimRight(cmp.Or(p.OpenAIBase(), p.Base(provider.Responses)), "/") } -// filmsCustom is whether p makes model at its OpenAI-shaped videos API, as -// its model list says (customVideomakers). +// filmsCustom is whether p makes model as its model list says +// (customVideomakers): at its OpenAI-shaped videos API, or, at Volcengine +// Ark, at Ark's tasks (arkFilms). func filmsCustom(p provider.Provider, model string) bool { return slices.ContainsFunc(customVideomakers(p), func(m catalog.Model) bool { return m.ID == model }) } +// arkVideoModel is whether id, a model of a Volcengine Ark key's list, is +// one of Ark's Seedance video models (doubao-seedance-1-0-pro-250528, +// doubao-seedance-2-0-260128…). +func arkVideoModel(id string) bool { + return strings.Contains(strings.ToLower(id), "seedance") +} + +// arkFilms is whether p makes model at Volcengine Ark's asynchronous +// content-generation tasks (/contents/generations/tasks, 火山方舟 +// 视频生成 API, https://www.volcengine.com/docs/82379/1520757): the +// preset's Agent Plan's Seedance, or a Seedance model of any other Ark +// key. Ark has no OpenAI-shaped videos API, so such a key's video models +// are never asked at /videos. +func arkFilms(p provider.Provider, model string) bool { + if p.IsRemoteMagpie() { + return false + } + if p.Preset == "volcengine" && slices.ContainsFunc(p.PlanVideos(), func(m catalog.Model) bool { return m.ID == model }) { + return true + } + return isArk(p) && filmsCustom(p, model) +} + +// arkTasks is where p, at Volcengine Ark, starts and is asked after a video. +func arkTasks(p provider.Provider) string { + return cmp.Or(strings.TrimRight(p.Base(provider.Responses), "/"), strings.TrimRight(p.Base(provider.Chat), "/")) + "/contents/generations/tasks" +} + // keyMark is the mark of the key p sends with, in the id of a video it // started at its OpenAI-shaped videos API: the vendor keeps a video for the // key that started it, so it is asked after on that key, whichever comes @@ -696,7 +741,7 @@ func asOurs(b []byte, p provider.Provider, id string) (map[string]any, error) { // filmsOpenAI is whether p makes videos at an OpenAI-shaped videos API: // another magpie, or a provider whose model list marks video models. func filmsOpenAI(p provider.Provider) bool { - return p.IsRemoteMagpie() || len(customVideomakers(p)) > 0 + return p.IsRemoteMagpie() || len(customVideomakers(p)) > 0 && !isArk(p) } // remoteVideoURL is where another magpie, or a provider's OpenAI-shaped @@ -712,8 +757,8 @@ func (s *Server) videoStatus(ctx context.Context, p provider.Provider, vendorID } var st videoState at := strings.TrimRight(p.Base(provider.Responses), "/") + "/videos/" + url.PathEscape(vendorID) - if p.Preset == "volcengine" { - at = strings.TrimRight(p.Base(provider.Responses), "/") + "/contents/generations/tasks/" + url.PathEscape(vendorID) + if p.Preset == "volcengine" || isArk(p) { + at = arkTasks(p) + "/" + url.PathEscape(vendorID) } b, code, err := s.sendAs(ctx, p, http.MethodGet, at, "", nil, true) if err != nil { @@ -957,6 +1002,9 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Pro return videoStart{p: p}, code, errors.New(msg) } p, keys = cs[0].p, cs[1:] + // an Ark key's video is a task of that key's account: its id names + // the key, as a plan's does, and it is asked after there + onKey = isArk(p) } else if makesMiniMaxVideo(p, model) { // on the first key a chat for the model would go to that the // calling key may use, the next while one's plan doesn't make H3 @@ -987,13 +1035,13 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Pro } } v := videoStart{p: p, remote: p.IsRemoteMagpie(), onKey: onKey} - v.custom = !v.remote && filmsCustom(p, model) - volcengine := p.Preset == "volcengine" && slices.ContainsFunc(p.PlanVideos(), func(m catalog.Model) bool { return m.ID == model }) + volcengine := arkFilms(p, model) + v.custom = !v.remote && !volcengine && filmsCustom(p, model) minimax := !v.remote && !v.custom && makesMiniMaxVideo(p, model) // any grok-imagine-video*, not only those listed: the vendor's newer ones work before magpie names them if !v.remote && !v.custom && !volcengine && !minimax && (!drawsGrok(p) || !strings.HasPrefix(model, grokVideoFamily)) { v.unfit = true - return v, 400, fmt.Errorf(`%s/%s can't make videos: magpie makes videos with a Grok subscription's grok-imagine-video, Volcengine Agent Plan's Seedance models, a MiniMax API key's MiniMax-H3 models, another magpie's, and a provider's models its own model list marks "kind": "video" or that you mark a Video model (right-click the model in the provider's editor: Makes…)`, p.ID, model) + return v, 400, fmt.Errorf(`%s/%s can't make videos: magpie makes videos with a Grok subscription's grok-imagine-video, Volcengine Agent Plan's or an Ark key's Seedance models, a MiniMax API key's MiniMax-H3 models, another magpie's, and a provider's models its own model list marks "kind": "video" or that you mark a Video model (right-click the model in the provider's editor: Makes…)`, p.ID, model) } // another magpie is asked at its videos API, which says itself what // it can't make @@ -1005,7 +1053,7 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Pro // magpie's is: OpenAI's body, its answer its own at, field, body = videoBase(p)+"/videos", "id", remoteVideoBody(model, f) case volcengine: - at, field, body = strings.TrimRight(p.Base(provider.Responses), "/")+"/contents/generations/tasks", "id", volcengineVideoBody(model, f) + at, field, body = arkTasks(p), "id", volcengineVideoBody(model, f) case minimax: var err error if body, err = minimaxVideoBody(model, f); err != nil { @@ -1040,8 +1088,9 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Pro // videoAsker is p on a key or account the calling key may use, to ask // after a video (#905), as starting one is held: a video at the -// OpenAI-shaped videos API of a provider set up with a base URL on the key -// that started it, which the calling key must be allowed; any other on the +// OpenAI-shaped videos API of a provider set up with a base URL, or at an +// Ark key's tasks, on the key that started it, which the calling key must +// be allowed; any other on the // first key or account it may use, as videosCreate picks. What the calling // key is told when it may use none, else "". func videoAsker(r *http.Request, p provider.Provider) (provider.Provider, string) { @@ -1049,7 +1098,7 @@ func videoAsker(r *http.Request, p provider.Provider) (provider.Provider, string if !held { return p, "" } - if !p.IsRemoteMagpie() && (filmsOpenAI(p) || filmsMiniMax(p)) { + if !p.IsRemoteMagpie() && (filmsOpenAI(p) || filmsMiniMax(p) || isArk(p) && len(customVideomakers(p)) > 0) { if p.Key == "" && p.Account == nil || accountAllowed(who, candidate{p: p}) { return p, "" } diff --git a/internal/gateway/video_ark_key_test.go b/internal/gateway/video_ark_key_test.go new file mode 100644 index 000000000..b0eab1e9a --- /dev/null +++ b/internal/gateway/video_ark_key_test.go @@ -0,0 +1,135 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// arkKeyVideos is a Volcengine Ark pay-as-you-go endpoint (/api/v3) that +// makes Seedance videos at its content-generation tasks, answering with +// the replies captured from Ark (volcengine_fixtures_test.go), and 404 at +// an OpenAI-shaped /videos, which Ark doesn't have. +type arkKeyVideos struct { + *httptest.Server + mu sync.Mutex + paths []string + bodies []string + keys []string + polled int +} + +func newArkKeyVideos(t *testing.T) *arkKeyVideos { + t.Helper() + a := &arkKeyVideos{} + a.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + a.mu.Lock() + defer a.mu.Unlock() + a.paths = append(a.paths, r.Method+" "+r.URL.Path) + a.bodies = append(a.bodies, string(body)) + a.keys = append(a.keys, r.Header.Get("Authorization")) + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && r.URL.Path == "/api/v3/contents/generations/tasks": + io.WriteString(w, volcengineVideoCreateResponse) + case r.Method == http.MethodGet && r.URL.Path == "/api/v3/contents/generations/tasks/cgt-20261008165954-4sc9n": + a.polled++ + if a.polled == 1 { + io.WriteString(w, volcengineVideoRunningResponse) + } else { + io.WriteString(w, strings.Replace(volcengineVideoSucceededResponse, "VIDEO_URL", a.URL+"/ark/video.mp4", 1)) + } + case r.Method == http.MethodGet && r.URL.Path == "/ark/video.mp4": + w.Header().Set("Content-Type", "video/mp4") + io.WriteString(w, "ark-video-bytes") + default: + w.WriteHeader(404) + io.WriteString(w, `{"error":{"code":"NotFound","message":"The specified resource is not found."}}`) + } + })) + t.Cleanup(a.Close) + return a +} + +// A Volcengine Ark key that isn't the Agent Plan's (pay-as-you-go, or an +// Ark endpoint added by hand) makes its Seedance models' videos at Ark's +// content-generation tasks, not at an OpenAI /videos Ark doesn't have +// (axelburks on Discord): a caller's OpenAI-shaped request is turned into +// Ark's, and its poll and download asked on the key that started it. +func TestArkKeyMakesSeedanceVideos(t *testing.T) { + fresh(t) + a := newArkKeyVideos(t) + was := isArk + isArk = func(p provider.Provider) bool { return p.ID == "ark" } + t.Cleanup(func() { isArk = was }) + if err := provider.Save(provider.Provider{ID: "ark", Name: "Volcengine Ark", Chat: a.URL + "/api/v3", Key: "key", + Models: []string{"doubao-seed-2.1-pro", "doubao-seedance-2-0-260128"}}); err != nil { + t.Fatal(err) + } + p, err := provider.Find("ark") + if err != nil { + t.Fatal(err) + } + ms := Videomakers(*p) + if !slices.ContainsFunc(ms, func(m catalog.Model) bool { return m.ID == "doubao-seedance-2-0-260128" }) || + slices.ContainsFunc(ms, func(m catalog.Model) bool { return m.ID == "doubao-seed-2.1-pro" }) { + t.Fatalf("Ark key's video models: %+v", ms) + } + + s := New() + code, obj, raw, _ := request(t, s, http.MethodPost, "/v1/videos", "application/json", + `{"model":"ark/doubao-seedance-2-0-260128","prompt":"一只喜鹊飞过","seconds":"5","size":"1280x720","input_reference":"data:image/png;base64,iVBORw0KGgo="}`) + if code != 200 || obj["status"] != "queued" || obj["model"] != "ark/doubao-seedance-2-0-260128" { + t.Fatalf("create: %d %s", code, raw) + } + id, _ := obj["id"].(string) + if !strings.HasPrefix(id, "video_ark.cgt-20261008165954-4sc9n.") || !strings.HasSuffix(id, "."+keyMark(*p)) { + t.Fatalf("id %q doesn't name Ark's task and the key", id) + } + code, obj, raw, _ = request(t, s, http.MethodGet, "/v1/videos/"+id, "", "") + if code != 200 || obj["status"] != "in_progress" { + t.Fatalf("running: %d %s", code, raw) + } + code, obj, raw, _ = request(t, s, http.MethodGet, "/v1/videos/"+id, "", "") + if code != 200 || obj["status"] != "completed" || obj["seconds"] != "5" || obj["model"] != "ark/doubao-seedance-2.0-mini" { + t.Fatalf("succeeded: %d %s", code, raw) + } + code, _, raw, head := request(t, s, http.MethodGet, "/v1/videos/"+id+"/content", "", "") + if code != 200 || string(raw) != "ark-video-bytes" || head.Get("Content-Type") != "video/mp4" { + t.Fatalf("content: %d %q", code, raw) + } + + a.mu.Lock() + defer a.mu.Unlock() + if a.paths[0] != "POST /api/v3/contents/generations/tasks" || slices.Contains(a.paths, "POST /api/v3/videos") { + t.Fatalf("asked at %v", a.paths) + } + for i, k := range a.keys { + if a.paths[i] != "GET /ark/video.mp4" && k != "Bearer key" { + t.Fatalf("%s sent with %q", a.paths[i], k) + } + } + var sent struct { + Model string `json:"model"` + Content []map[string]any `json:"content"` + Dur int `json:"duration"` + Ratio string `json:"ratio"` + Res string `json:"resolution"` + } + if err := json.Unmarshal([]byte(a.bodies[0]), &sent); err != nil { + t.Fatal(err) + } + if sent.Model != "doubao-seedance-2-0-260128" || sent.Dur != 5 || sent.Ratio != "16:9" || sent.Res != "720p" || len(sent.Content) != 2 || + sent.Content[0]["text"] != "一只喜鹊飞过" || sent.Content[1]["role"] != "first_frame" { + t.Fatalf("sent %s", a.bodies[0]) + } +}