Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: a MiniMax API key makes videos with H3 (_tigerqueen_05867)

yetoneb2d005bf383e
diff --git a/README.md b/README.md
index ef0db3308..be33a2699 100644
--- a/README.md
+++ b/README.md
@@ -274,7 +274,7 @@ Find them under Plugins › Discover › Gateway middleware. See [Gateway middle
- **Library**: write instructions, MCP servers, skills and subagents once; magpie writes them into each agent's files in its format, and removes only what it wrote.
- **Web search for any model**: a model that can't search gets magpie's search: a provider that can, or search APIs (Tavily, Brave, Exa, Firecrawl, You.com, DeepSeek, SearXNG), asked in the order you drag them into, each one able to be switched off without losing its key. An API can hold several keys: searches take turns over them (or use them in order with `pick=order`), a key refused lately is asked last, and Tavily keys show what each has used of its limit, in Settings and in `magpie search`. Any agent can mount the same search as an MCP server, with a `web_search` tool and a `web_fetch` tool that reads a page by its URL.
-- **Images and video**: an image tool for any agent over MCP, with the model you choose, and videos with a Grok subscription.
+- **Images and video**: an image tool for any agent over MCP, with the model you choose, and videos with a Grok subscription or a MiniMax API key (MiniMax H3).
- **Agents kept current**: the Agents page shows each CLI's version, updates it the way it was installed, and gives the commands for the ones you don't have.
- **WSL**: on Windows, agents inside WSL distros are wired too, and their sessions counted.
- **Keep awake**, light and dark, and your theme's look on [Omarchy](https://omarchy.org).
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 540c40d5f..ba42c23fd 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -274,7 +274,7 @@ magpie plugin options model-map '{"mapping": {"fast": "deepseek/deepseek-chat"}}
- **资料库**:指令、MCP 服务器、技能和子代理只写一次,magpie 按每个 Agent 的格式写进它的文件,删除时只删自己写的部分。
- **任何模型都能联网搜索**:不能搜索的模型由 magpie 代为搜索,用能搜索的 provider 或搜索 API(Tavily、Brave、Exa、Firecrawl、You.com、DeepSeek、SearXNG),按你拖好的顺序调用,每个都能单独关闭而不删除密钥。一个 API 可以填多个密钥:搜索默认轮流使用(`pick=order` 则按顺序),最近被拒的密钥最后才用;Tavily 的每个密钥用了多少额度,在设置页和 `magpie search` 里都能看到。任何 Agent 都能把同一个搜索挂成 MCP 服务器,提供 `web_search` 工具和按 URL 读取网页的 `web_fetch` 工具。
-- **图片和视频**:通过 MCP 给任何 Agent 一个生图工具,用你选的模型;有 Grok 订阅还能生成视频。
+- **图片和视频**:通过 MCP 给任何 Agent 一个生图工具,用你选的模型;有 Grok 订阅或 MiniMax API Key(MiniMax H3)还能生成视频。
- **Agent 保持最新**:Agents 页显示每个 CLI 的版本,按当初的安装方式更新,没装的也给出安装命令。
- **WSL**:在 Windows 上,WSL 发行版里的 Agent 一样能配置,会话也一样统计。
- **保持唤醒**、浅色和深色,在 [Omarchy](https://omarchy.org) 上跟随你的主题。
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 372a9897d..6c54040df 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -475,6 +475,43 @@ 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.
+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
+with the H3 models, MiniMax-H3, -Highspeed, -Lite and -Max
+([`video_minimax.go`](../../internal/gateway/video_minimax.go),
+`minimaxVideoModels`). They are video models only (`Films`), listed by
+`Videomakers` and never added to a chat list. A video starts at
+`<host>/v2/video_generation` on that key's own host, so international and
+Chinese keys each reach their platform, and is polled at
+`<host>/v2/query/video_generation/<task_id>`. Its MP4 is `task.content.url`,
+fetched as other vendors' video URLs are (`vendorClient`). `minimaxVideoBody`
+sends the prompt and images in `content` (`first_frame` from
+`input_reference`, `last_frame` from the request's `last_frame`, references
+as `reference_image`). It turns away frames and references together, or more
+than 9 references, with a 400 before MiniMax is asked. The duration is 5
+unless set, raised to the model's shortest (4, or 5 for Max) and cut at 15.
+The resolution is the request's own `resolution`, else derived from `size`'s
+shorter side among the model's resolutions (H3 768P/2K, Highspeed 768P,
+Lite and Max 768P/480P). The ratio is the nearest of MiniMax's to `size`.
+None is sent with a frame, since the video takes the image's shape. Text
+alone, and Lite's references, default to 16:9. No `callback_url` is ever
+sent. Ids carry the key's mark (`markedKey`), as a custom provider's do,
+and a key whose plan doesn't make H3 (codes 2061/2068/2057: a Token Plan
+key) hands the video to the provider's next key. Failures are said for what
+they are before MiniMax's own words (`minimaxWhy`, `minimaxError`): a bad
+key (1004, 2049, 401), an empty pay-as-you-go balance (1008, 402), refused
+content (1026, 1027), a plan without H3, and the rate limit (1002, 1045,
+429). A failed task's `error.code` is explained the same way.
+`AutoVideomaker` puts a MiniMax key after every other video maker: H3 is
+paid by the second, so a subscription that made the videos before keeps
+making them, and generate_video, which names no model, uses MiniMax-H3 only
+when nothing else makes videos. Covered by `TestMiniMaxKeysMakeH3Videos`,
+`TestMiniMaxVideoIsStartedPolledAndFetched`, `TestMiniMaxVideoBody`,
+`TestMiniMaxVideoFailuresSayWhy`, `TestImageMCPMakesMiniMaxVideos`,
+`TestMiniMaxComesAfterOtherVideomakers` and
+`TestMiniMaxVideoMovesPastATokenPlanKey`.
+
## Turning provider search off
[Settings](../../internal/settings/settings.go)' `searcher: "off"` disables magpie's provider-assisted search,
@@ -915,6 +952,7 @@ vendor) and the other `TestTool*` tests.
Covered by `TestImageMCPDrawsAndServesTheImage`, `TestImageMCPSaysWhenOff`,
`TestImageMCPGuarded`, `TestImageMCPHeldToKeyLimit`,
`TestImageMCPSlowDrawingIsWaitedOn`, `TestImageMCPMakesVideos`,
+`TestImageMCPMakesMiniMaxVideos`,
`TestImageMCPIsServed` and `image-mcp.test.cjs`.
## Side models magpie picks: allowance first
diff --git a/internal/gateway/video.go b/internal/gateway/video.go
index 800202286..f0c7b941b 100644
--- a/internal/gateway/video.go
+++ b/internal/gateway/video.go
@@ -65,8 +65,9 @@ const videoTimeout = 5 * time.Minute
// Videomakers are the models a provider can make videos with: a Grok
// subscription's, another magpie's, a preset plan's models when magpie
-// implements that vendor's video API, and those a provider's own model list
-// marks as video models (customVideomakers).
+// implements that vendor's video API, a MiniMax API key's H3 models
+// (video_minimax.go), and those a provider's own model list marks as video
+// models (customVideomakers).
func Videomakers(p provider.Provider) []catalog.Model {
if p.IsRemoteMagpie() {
out := catalog.LiveVideomakers(p.ID)
@@ -78,6 +79,9 @@ func Videomakers(p provider.Provider) []catalog.Model {
if out := p.PlanVideos(); len(out) > 0 {
return out
}
+ if filmsMiniMax(p) {
+ return minimaxVideomakers(p)
+ }
if !drawsGrok(p) {
return customVideomakers(p)
}
@@ -97,7 +101,7 @@ func Videomakers(p provider.Provider) []catalog.Model {
// model's name alone makes none of them one: a list that doesn't say so,
// and a user who doesn't, leave the provider making no videos.
func customVideomakers(p provider.Provider) []catalog.Model {
- if p.Account != nil || p.IsRemoteMagpie() || len(p.PlanVideos()) > 0 || videoBase(p) == "" {
+ if p.Account != nil || p.IsRemoteMagpie() || len(p.PlanVideos()) > 0 || filmsMiniMax(p) || videoBase(p) == "" {
return nil
}
out := catalog.LiveVideomakers(p.ID)
@@ -151,7 +155,7 @@ func markedKey(p provider.Provider, by string) (provider.Provider, bool) {
return p, by == "0"
}
for _, k := range p.KeysOn() {
- if q := p.WithKey(k); keyMark(q) == by && videoBase(q) != "" {
+ if q := p.WithKey(k); keyMark(q) == by && (videoBase(q) != "" || filmsMiniMax(q)) {
return q, true
}
}
@@ -171,17 +175,26 @@ func videomaker() (string, bool) {
// AutoVideomaker is the model a request that names none makes its video
// with: the first model of the first provider that makes any. "" when none
-// can.
+// can. A MiniMax API key's H3 comes after every other: it is paid by the
+// second from the key's balance, and a key set up for chat would
+// otherwise take videos a subscription made before.
func AutoVideomaker() string {
+ paid := ""
for _, p := range provider.All() {
if !p.On() || p.DecideOnly() {
continue
}
if ms := Videomakers(p); len(ms) > 0 {
+ if filmsMiniMax(p) {
+ if paid == "" {
+ paid = p.ID + "/" + ms[0].ID
+ }
+ continue
+ }
return p.ID + "/" + ms[0].ID
}
}
- return ""
+ return paid
}
// bareVideomaker is the provider that makes videos with model named without
@@ -218,6 +231,7 @@ const grokVideoFamily = "grok-imagine-video"
type filming struct {
Model, Prompt, Seconds, Size string
Start *picture // the first frame to animate
+ End *picture // the last frame, where the video ends (MiniMax)
References []picture // images the video draws its subjects from
// the request's other fields, which magpie doesn't read: a provider's
// own videos API takes them as they came (Agnes's mode, aspect_ratio;
@@ -226,7 +240,7 @@ type filming struct {
}
// filmingRead are the fields of a videos request magpie reads itself.
-var filmingRead = []string{"model", "prompt", "seconds", "size", "input_reference", "reference_images", "reference_images[]"}
+var filmingRead = []string{"model", "prompt", "seconds", "size", "input_reference", "last_frame", "reference_images", "reference_images[]"}
// readFilming reads a videos request: JSON, or the multipart form OpenAI's
// takes, the image to start from its input_reference.
@@ -260,6 +274,13 @@ func readFilming(r *http.Request) (filming, error) {
}
f.Start = &pic
}
+ if fhs := m.File["last_frame"]; len(fhs) > 0 {
+ pic, err := readPart(fhs[0])
+ if err != nil {
+ return f, err
+ }
+ f.End = &pic
+ }
for _, k := range []string{"reference_images", "reference_images[]"} {
for _, fh := range m.File[k] {
pic, err := readPart(fh)
@@ -280,6 +301,7 @@ func readFilming(r *http.Request) (filming, error) {
Seconds json.RawMessage `json:"seconds"`
Size string `json:"size"`
InputReference json.RawMessage `json:"input_reference"`
+ LastFrame json.RawMessage `json:"last_frame"`
ReferenceImages json.RawMessage `json:"reference_images"`
}
if err := json.Unmarshal(body, &in); err != nil {
@@ -306,6 +328,13 @@ func readFilming(r *http.Request) (filming, error) {
}
f.Start = &pic
}
+ if srcs := imageSources(in.LastFrame); len(srcs) > 0 {
+ pic, err := pictureOf(srcs[0])
+ if err != nil {
+ return f, err
+ }
+ f.End = &pic
+ }
for _, src := range imageSources(in.ReferenceImages) {
pic, err := pictureOf(src)
if err != nil {
@@ -548,6 +577,14 @@ func videoMaker(id string) (p provider.Provider, vendorID string, started time.T
return p, "", started, fmt.Errorf("%q isn't the id of a video magpie is making", id)
}
found, ferr := provider.Find(pid)
+ if ferr == nil && filmsMiniMax(*found) {
+ // a MiniMax task is its key's account's: asked on that key
+ q, ok := markedKey(*found, by)
+ if !ok {
+ return p, "", started, fmt.Errorf("this video was started with a key of %s that is no longer on: turn it back on to get the video", found.Name)
+ }
+ return q, vendorID, started, nil
+ }
if ferr == nil && !drawsGrok(*found) && !found.IsRemoteMagpie() && len(found.PlanVideos()) == 0 && len(customVideomakers(*found)) > 0 {
// asked on the key that started it
q, ok := markedKey(*found, by)
@@ -602,6 +639,9 @@ func remoteVideoBody(model string, f filming) []byte {
if f.Start != nil {
req["input_reference"] = f.Start.dataURL()
}
+ if f.End != nil {
+ req["last_frame"] = f.End.dataURL()
+ }
var refs []string
for _, pic := range f.References {
refs = append(refs, pic.dataURL())
@@ -641,6 +681,9 @@ func remoteVideoURL(p provider.Provider, vendorID, suffix string) string {
// videoStatus asks the vendor how a video is going.
func (s *Server) videoStatus(ctx context.Context, p provider.Provider, vendorID string) (videoState, int, error) {
+ if filmsMiniMax(p) {
+ return s.minimaxVideoStatus(ctx, p, vendorID)
+ }
var st videoState
at := strings.TrimRight(p.Base(provider.Responses), "/") + "/videos/" + url.PathEscape(vendorID)
if p.Preset == "volcengine" {
@@ -686,7 +729,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
if f.Model == "" {
m, ok := videomaker()
if !ok {
- fail(400, "no model to make videos with: sign in to a Grok subscription or set up a provider that makes videos, and leave Settings → Images → Image generation on, or name one")
+ fail(400, "no model to make videos with: sign in to a Grok subscription or set up a provider that makes videos (a MiniMax API key makes them with MiniMax-H3), and leave Settings → Images → Image generation on, or name one")
return
}
f.Model, call.Model = m, m
@@ -872,6 +915,16 @@ 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:]
+ } 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
+ // (a Token Plan's); the video's id names the key it is asked on
+ cs, code, msg := s.onKeys(r, p, model, f.Model)
+ if code != 0 {
+ return videoStart{p: p}, code, errors.New(msg)
+ }
+ p, keys = cs[0].p, cs[1:]
+ onKey = true
} else if !p.IsRemoteMagpie() && p.PlansMixed() {
// keys on plans of their own (KeyAccount.Plan): sent on a key
// whose plan makes the model, the Agent Plan's Seedance on the
@@ -894,10 +947,11 @@ 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 })
+ 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 && (!drawsGrok(p) || !strings.HasPrefix(model, grokVideoFamily)) {
+ 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, 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 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
@@ -910,6 +964,12 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Pro
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)
+ case minimax:
+ var err error
+ if body, err = minimaxVideoBody(model, f); err != nil {
+ return v, 400, err
+ }
+ at, field = minimaxHost(p)+"/v2/video_generation", "task_id"
default:
var err error
if body, err = grokVideoBody(model, f); err != nil {
@@ -920,10 +980,18 @@ func (s *Server) startVideo(ctx context.Context, r *http.Request, p provider.Pro
b, code, err := s.send(ctx, p, at, "application/json", body, true)
// a key answering 404 that it doesn't serve the model hands it to the
// next (#1657), as a drawing does; the id names the key that started it
- for ; err != nil && len(keys) > 0 && ctx.Err() == nil && keyLacksModel(code, err); keys = keys[1:] {
+ for ; err != nil && len(keys) > 0 && ctx.Err() == nil && (keyLacksModel(code, err) || minimax && minimaxLacksH3(b)); keys = keys[1:] {
p = keys[0].p
b, code, err = s.send(ctx, p, at, "application/json", body, true)
}
+ if minimax {
+ if err != nil {
+ err = minimaxError(code, b, err)
+ } else if msg, mcode := minimaxSaid(b); msg != "" {
+ // an answer of 200 that says it failed (base_resp)
+ code, err = 502, minimaxError(0, b, fmt.Errorf("%s: %s%s", p.Name, msg, codeUnlessSaid(msg, mcode)))
+ }
+ }
v.p, v.answer = p, b
return v, code, err
}
@@ -939,7 +1007,7 @@ func videoAsker(r *http.Request, p provider.Provider) (provider.Provider, string
if !held {
return p, ""
}
- if !p.IsRemoteMagpie() && filmsOpenAI(p) {
+ if !p.IsRemoteMagpie() && (filmsOpenAI(p) || filmsMiniMax(p)) {
if p.Key == "" && p.Account == nil || accountAllowed(who, candidate{p: p}) {
return p, ""
}
diff --git a/internal/gateway/video_minimax.go b/internal/gateway/video_minimax.go
new file mode 100644
index 000000000..93be22a70
--- /dev/null
+++ b/internal/gateway/video_minimax.go
@@ -0,0 +1,316 @@
+package gateway
+
+import (
+ "cmp"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "regexp"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/yetone/magpie/internal/catalog"
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// MiniMax makes videos with its H3 models on any MiniMax API key, at its
+// own asynchronous API (platform.minimax.io/docs/api-reference/
+// video-generation-v2-create): POST <host>/v2/video_generation answers with
+// a task_id, GET <host>/v2/query/video_generation/<task_id> with the task,
+// whose content.url is the MP4 once it has succeeded. The host is the
+// key's own: api.minimax.io for the international platform,
+// api.minimaxi.com (or api.minimax.cn) for the Chinese one. H3 is paid
+// from the pay-as-you-go balance; a Token Plan key or a video package
+// doesn't make it, which the vendor says with its own code (2061, 2068).
+
+// minimaxVideoModels are the H3 models, in the vendor's order. They make
+// videos only: none of them is ever a chat model.
+var minimaxVideoModels = []catalog.Model{
+ {ID: "MiniMax-H3", Name: "MiniMax H3"},
+ {ID: "MiniMax-H3-Highspeed", Name: "MiniMax H3 Highspeed"},
+ {ID: "MiniMax-H3-Lite", Name: "MiniMax H3 Lite"},
+ {ID: "MiniMax-H3-Max", Name: "MiniMax H3 Max"},
+}
+
+// minimaxVideoLimits is what each H3 model takes: its resolutions, the
+// first its default, and its shortest video in seconds. All go to 15.
+var minimaxVideoLimits = map[string]struct {
+ resolutions []string
+ minSeconds int
+}{
+ "MiniMax-H3": {[]string{"768P", "2K"}, 4},
+ "MiniMax-H3-Highspeed": {[]string{"768P"}, 4},
+ "MiniMax-H3-Lite": {[]string{"768P", "480P"}, 4},
+ "MiniMax-H3-Max": {[]string{"768P", "480P"}, 5},
+}
+
+// minimaxVideoRatios are the aspect ratios MiniMax's video API takes, besides
+// adaptive (the images' own).
+var minimaxVideoRatios = []string{"21:9", "16:9", "4:3", "1:1", "3:4", "9:16"}
+
+// isMiniMaxHost is whether host is MiniMax's API. A var so tests can point a
+// MiniMax provider at a fake server, as isArk does.
+var isMiniMaxHost = func(host string) bool {
+ switch strings.ToLower(host) {
+ case "api.minimax.io", "api.minimaxi.com", "api.minimax.cn":
+ return true
+ }
+ return false
+}
+
+// minimaxHost is scheme://host of the MiniMax API p's key is for, from its
+// Chat, Anthropic or Responses base: "" when p isn't MiniMax's.
+func minimaxHost(p provider.Provider) string {
+ for _, base := range []string{p.Base(provider.Chat), p.Base(provider.Anthropic), p.Base(provider.Responses)} {
+ u, err := url.Parse(strings.TrimSpace(base))
+ if err != nil || u.Host == "" || !isMiniMaxHost(u.Host) {
+ continue
+ }
+ return u.Scheme + "://" + u.Host
+ }
+ return ""
+}
+
+// filmsMiniMax is whether p is a MiniMax API key, which makes videos with
+// the H3 models: not a subscription's account, another magpie or a plugin.
+func filmsMiniMax(p provider.Provider) bool {
+ return p.Account == nil && !p.IsRemoteMagpie() && !p.IsPlugin() && minimaxHost(p) != ""
+}
+
+// minimaxVideomakers are the H3 models as p's.
+func minimaxVideomakers(p provider.Provider) []catalog.Model {
+ out := slices.Clone(minimaxVideoModels)
+ for i := range out {
+ out[i].Provider, out[i].Films = p.ID, true
+ }
+ return out
+}
+
+// makesMiniMaxVideo is whether model is one of p's H3 models.
+func makesMiniMaxVideo(p provider.Provider, model string) bool {
+ return filmsMiniMax(p) && slices.ContainsFunc(minimaxVideoModels, func(m catalog.Model) bool { return m.ID == model })
+}
+
+// minimaxVideoBody is f as MiniMax's video API takes it: the prompt and
+// images in content, the images' roles telling a first or last frame from a
+// subject reference, and the duration, resolution and ratio each model
+// takes. What it can't take (frames and references together) is said here,
+// before the vendor is asked and nothing is spent.
+func minimaxVideoBody(model string, f filming) ([]byte, error) {
+ lim, ok := minimaxVideoLimits[model]
+ if !ok {
+ lim = minimaxVideoLimits["MiniMax-H3"]
+ }
+ frames := f.Start != nil || f.End != nil
+ if frames && len(f.References) > 0 {
+ return nil, errors.New("MiniMax makes a video from a first or last frame, or from reference images, not both: send one or the other")
+ }
+ if len(f.References) > 9 {
+ return nil, fmt.Errorf("MiniMax takes at most 9 reference images, not %d", len(f.References))
+ }
+ content := []map[string]any{{"type": "text", "text": f.Prompt}}
+ add := func(pic picture, role string) {
+ content = append(content, map[string]any{"type": "image_url", "image_url": map[string]string{"url": pic.dataURL()}, "role": role})
+ }
+ if f.Start != nil {
+ add(*f.Start, "first_frame")
+ }
+ if f.End != nil {
+ add(*f.End, "last_frame")
+ }
+ for _, pic := range f.References {
+ add(pic, "reference_image")
+ }
+ // the length in whole seconds, 5 unless said, within the model's
+ seconds := 5
+ if f.Seconds != "" {
+ seconds, _ = strconv.Atoi(f.Seconds)
+ }
+ seconds = min(max(seconds, lim.minSeconds), 15)
+ req := map[string]any{"model": model, "content": content, "duration": seconds, "resolution": minimaxResolution(lim.resolutions, f)}
+ // with a frame the video takes the image's shape (the vendor ignores
+ // any other); text alone needs one, and Lite's references too
+ if !frames {
+ ratio := minimaxRatio(f)
+ if ratio == "" && (len(f.References) == 0 || model == "MiniMax-H3-Lite") {
+ ratio = "16:9"
+ }
+ if ratio != "" {
+ req["ratio"] = ratio
+ }
+ }
+ // what the caller set of MiniMax's own fields: prompt_expansion_mode
+ // (H3 Max), never where the vendor would call back to
+ if extra, ok := f.Extra["extra"].(map[string]any); ok && model == "MiniMax-H3-Max" {
+ req["extra"] = extra
+ }
+ return json.Marshal(req)
+}
+
+// minimaxResolution is the resolution a video is asked for: the caller's
+// own (resolution: "480P"), else by size's shorter side, among the model's;
+// the model's default when neither says.
+func minimaxResolution(allowed []string, f filming) string {
+ if s, ok := f.Extra["resolution"].(string); ok && strings.TrimSpace(s) != "" {
+ return strings.ToUpper(strings.TrimSpace(s)) // what the model can't make the vendor says
+ }
+ want := ""
+ switch pixelResolution(f.Size) {
+ case "1080p":
+ want = "2K"
+ case "720p":
+ want = "768P"
+ case "480p":
+ want = "480P"
+ }
+ if slices.Contains(allowed, want) {
+ return want
+ }
+ if want == "2K" || want == "480P" {
+ // the nearest it makes: 768P
+ if slices.Contains(allowed, "768P") {
+ return "768P"
+ }
+ }
+ return allowed[0]
+}
+
+// minimaxRatio is the ratio size names, or the caller's ratio field, as
+// one MiniMax takes: the nearest of its ratios. "" when neither says.
+func minimaxRatio(f filming) string {
+ size := strings.TrimSpace(f.Size)
+ if r, ok := f.Extra["ratio"].(string); ok && strings.TrimSpace(r) != "" {
+ size = strings.TrimSpace(r)
+ }
+ if strings.EqualFold(size, "adaptive") {
+ return "adaptive"
+ }
+ if a, b, ok := strings.Cut(size, ":"); ok {
+ size = a + "x" + b
+ }
+ return aspectAmong(size, minimaxVideoRatios)
+}
+
+// minimaxCode is the code MiniMax put at the end of its message: "insufficient
+// balance (1008)" is 1008.
+var minimaxCode = regexp.MustCompile(`\((\d{3,5})\)\s*$`)
+
+// minimaxSaid is what MiniMax's answer b says went wrong, and its code: its
+// OpenAI-shaped error, or the base_resp its older APIs answer with.
+func minimaxSaid(b []byte) (msg, code string) {
+ var e struct {
+ Error struct {
+ Type string `json:"type"`
+ Message string `json:"message"`
+ } `json:"error"`
+ BaseResp struct {
+ StatusCode int `json:"status_code"`
+ StatusMsg string `json:"status_msg"`
+ } `json:"base_resp"`
+ }
+ if json.Unmarshal(b, &e) != nil {
+ return "", ""
+ }
+ if msg = e.Error.Message; msg == "" && e.BaseResp.StatusCode != 0 {
+ return e.BaseResp.StatusMsg, strconv.Itoa(e.BaseResp.StatusCode)
+ }
+ if m := minimaxCode.FindStringSubmatch(msg); m != nil {
+ code = m[1]
+ }
+ return msg, code
+}
+
+// minimaxWhy is what a MiniMax error code (or, without one, its HTTP
+// status) means for the user: the key, the balance, the content or the
+// key's plan. "" when it is none of those.
+func minimaxWhy(code string, status int) string {
+ switch {
+ case code == "1004" || code == "2049" || code == "" && status == http.StatusUnauthorized:
+ return "MiniMax turned the API key away: it is wrong, or was deleted. Put a working key in the MiniMax provider"
+ case code == "1008" || code == "" && status == http.StatusPaymentRequired:
+ return "the MiniMax account is out of balance: H3 videos are paid from the pay-as-you-go balance. Top it up on MiniMax's platform"
+ case code == "1026":
+ return "MiniMax refused the prompt or images as sensitive content: change what the video asks for"
+ case code == "1027":
+ return "MiniMax refused the video it made as sensitive content: change what the video asks for"
+ case code == "2061" || code == "2068" || code == "2057":
+ return "this MiniMax key's plan doesn't make H3 videos: a Token Plan or video package doesn't cover H3; it needs a pay-as-you-go API key"
+ case code == "1002" || code == "1045" || code == "" && status == http.StatusTooManyRequests:
+ return "MiniMax is making as many videos as this account may at once, or was asked too often: try again shortly"
+ }
+ return ""
+}
+
+// minimaxLacksH3 is whether MiniMax said the key's plan doesn't make the
+// model: the next key, a pay-as-you-go one, may.
+func minimaxLacksH3(b []byte) bool {
+ _, code := minimaxSaid(b)
+ return code == "2061" || code == "2068" || code == "2057"
+}
+
+// minimaxError is err (MiniMax turning a video away with status and body
+// b) with what it means first: a bad key, an empty balance and refused
+// content each said for what they are.
+func minimaxError(status int, b []byte, err error) error {
+ _, code := minimaxSaid(b)
+ if why := minimaxWhy(code, status); why != "" {
+ return fmt.Errorf("%s — %w", why, err)
+ }
+ return err
+}
+
+// minimaxTask is a MiniMax video task as its query answers it.
+type minimaxTask struct {
+ Task struct {
+ ID string `json:"id"`
+ Model string `json:"model"`
+ Status string `json:"status"`
+ Duration float64 `json:"duration"`
+ Content struct {
+ URL string `json:"url"`
+ } `json:"content"`
+ Error struct {
+ Code json.RawMessage `json:"code"`
+ Message string `json:"message"`
+ } `json:"error"`
+ } `json:"task"`
+}
+
+// minimaxVideoStatus asks MiniMax how a video task is going, as a videoState.
+func (s *Server) minimaxVideoStatus(ctx context.Context, p provider.Provider, taskID string) (videoState, int, error) {
+ var st videoState
+ at := minimaxHost(p) + "/v2/query/video_generation/" + url.PathEscape(taskID)
+ b, code, err := s.sendAs(ctx, p, http.MethodGet, at, "", nil, true)
+ if err != nil {
+ return st, code, minimaxError(code, b, err)
+ }
+ var t minimaxTask
+ if err := json.Unmarshal(b, &t); err != nil || t.Task.Status == "" {
+ if msg, mcode := minimaxSaid(b); msg != "" {
+ return st, 502, minimaxError(0, b, fmt.Errorf("%s: %s", p.Name, msg+codeUnlessSaid(msg, mcode)))
+ }
+ return st, 502, fmt.Errorf("%s's answer isn't a video task's: %.200s", p.Name, b)
+ }
+ st.Status, st.Model, st.Duration = t.Task.Status, t.Task.Model, t.Task.Duration
+ st.Video.URL = t.Task.Content.URL
+ if t.Task.Status == "failed" {
+ st.Error.Code = strings.Trim(string(t.Task.Error.Code), `"`)
+ st.Error.Message = t.Task.Error.Message
+ if why := minimaxWhy(st.Error.Code, 0); why != "" {
+ st.Error.Message = why + " — MiniMax: " + cmp.Or(t.Task.Error.Message, "the video failed") + " (" + st.Error.Code + ")"
+ }
+ }
+ return st, 200, nil
+}
+
+// codeUnlessSaid is " (code)" when msg doesn't end with it already.
+func codeUnlessSaid(msg, code string) string {
+ if code == "" || strings.HasSuffix(strings.TrimSpace(msg), "("+code+")") {
+ return ""
+ }
+ return " (" + code + ")"
+}
diff --git a/internal/gateway/video_minimax_test.go b/internal/gateway/video_minimax_test.go
new file mode 100644
index 000000000..07649da2b
--- /dev/null
+++ b/internal/gateway/video_minimax_test.go
@@ -0,0 +1,480 @@
+package gateway
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/catalog"
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// MiniMax's answers as its docs give them (platform.minimax.io/docs/
+// api-reference/video-generation-v2-create and -query, 2026-10-29): the
+// create's task_id, the query's succeeded and failed tasks, and its errors.
+const (
+ minimaxVideoCreateResponse = `{"task_id":"424010985738629"}`
+ minimaxVideoSucceededResponse = `{"task":{"id":"424010985738629","model":"MiniMax-H3","status":"succeeded","created_at":1785125529,"updated_at":1785125946,"content":{"url":"VIDEO_URL"},"resolution":"2K","duration":5,"usage":{"total_seconds":5,"input_seconds":0,"output_seconds":5,"input_image_count":0},"ratio":"16:9","task_type":"generation","modality":"video"}}`
+ minimaxVideoFailedResponse = `{"task":{"id":"424010985738630","model":"MiniMax-H3","status":"failed","error":{"code":"1026","message":"video description contains sensitive content"},"created_at":1785125529,"updated_at":1785125700,"resolution":"2K","duration":5,"usage":{},"ratio":"16:9","task_type":"generation","modality":"video"}}`
+ minimax401 = `{"type":"error","error":{"type":"authorized_error","message":"login fail: Please carry the API secret key in the 'Authorization' field of the request header (1004)","http_code":"401"},"request_id":"021785229015510a2c883cf675b9804d"}`
+ minimax402 = `{"type":"error","error":{"type":"insufficient_balance_error","message":"insufficient balance (1008)","http_code":"402"},"request_id":"021785229015510a2c883cf675b9804d"}`
+ minimax422 = `{"type":"error","error":{"type":"unprocessable_entity_error","message":"video description contains sensitive content (1026)","http_code":"422"},"request_id":"021785229015510a2c883cf675b9804d"}`
+)
+
+// the succeeded task while it is still being made: the same task, queued
+// or running, with no video yet
+func minimaxPending(status string) string {
+ s := strings.Replace(minimaxVideoSucceededResponse, `"status":"succeeded"`, `"status":"`+status+`"`, 1)
+ return strings.Replace(s, `"content":{"url":"VIDEO_URL"},`, "", 1)
+}
+
+// fakeMiniMax is MiniMax's video API on a test server: the create answers
+// by what the prompt says, the task is queued, then running, then made
+// (or stays queued: STUCK), and the video is at its own path.
+type fakeMiniMax struct {
+ *httptest.Server
+ mu sync.Mutex
+ paths []string
+ bodies []string
+ auth []string
+ polls int
+}
+
+func newFakeMiniMax(t *testing.T) *fakeMiniMax {
+ f := &fakeMiniMax{}
+ f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.paths = append(f.paths, r.Method+" "+r.URL.Path)
+ f.bodies = append(f.bodies, string(body))
+ f.auth = append(f.auth, r.Header.Get("Authorization"))
+ if r.URL.Path == "/cdn/output.mp4" {
+ w.Header().Set("Content-Type", "video/mp4")
+ io.WriteString(w, "minimax-mp4-bytes")
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if r.Header.Get("Authorization") == "Bearer bad-key" {
+ w.WriteHeader(401)
+ io.WriteString(w, minimax401)
+ return
+ }
+ if r.Header.Get("Authorization") != "Bearer key" && r.Header.Get("Authorization") != "Bearer second-key" {
+ w.WriteHeader(401)
+ io.WriteString(w, minimax401)
+ return
+ }
+ switch {
+ case r.Method == http.MethodPost && r.URL.Path == "/v2/video_generation":
+ switch {
+ case strings.Contains(string(body), "BROKE"):
+ w.WriteHeader(402)
+ io.WriteString(w, minimax402)
+ case strings.Contains(string(body), "SENSITIVE"):
+ w.WriteHeader(422)
+ io.WriteString(w, minimax422)
+ case strings.Contains(string(body), "FAILING"):
+ io.WriteString(w, `{"task_id":"424010985738630"}`)
+ case strings.Contains(string(body), "STUCK"):
+ io.WriteString(w, `{"task_id":"424010985738699"}`)
+ default:
+ io.WriteString(w, minimaxVideoCreateResponse)
+ }
+ case r.Method == http.MethodGet && r.URL.Path == "/v2/query/video_generation/424010985738629":
+ f.polls++
+ switch f.polls {
+ case 1:
+ io.WriteString(w, minimaxPending("queued"))
+ case 2:
+ io.WriteString(w, minimaxPending("running"))
+ default:
+ io.WriteString(w, strings.Replace(minimaxVideoSucceededResponse, "VIDEO_URL", f.URL+"/cdn/output.mp4", 1))
+ }
+ case r.Method == http.MethodGet && r.URL.Path == "/v2/query/video_generation/424010985738630":
+ io.WriteString(w, minimaxVideoFailedResponse)
+ case r.Method == http.MethodGet && r.URL.Path == "/v2/query/video_generation/424010985738699":
+ io.WriteString(w, strings.Replace(minimaxPending("queued"), "424010985738629", "424010985738699", 1))
+ default:
+ w.WriteHeader(404)
+ io.WriteString(w, `{"type":"error","error":{"type":"not_found","message":"unexpected path"}}`)
+ }
+ }))
+ t.Cleanup(f.Close)
+ return f
+}
+
+func (f *fakeMiniMax) seen() (paths, bodies, auth []string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]string(nil), f.paths...), append([]string(nil), f.bodies...), append([]string(nil), f.auth...)
+}
+
+// minimaxProvider saves a MiniMax API key from preset (minimax or
+// minimax-cn) pointed at the fake, which stands in for MiniMax's host.
+func minimaxProvider(t *testing.T, preset, id string, up *fakeMiniMax) provider.Provider {
+ t.Helper()
+ was := isMiniMaxHost
+ t.Cleanup(func() { isMiniMaxHost = was })
+ host := strings.TrimPrefix(up.URL, "http://")
+ isMiniMaxHost = func(h string) bool { return h == host || was(h) }
+ p, err := provider.FromPreset(preset)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p.ID, p.Key = id, "key"
+ p.Chat, p.Anthropic = up.URL+"/v1", up.URL+"/anthropic"
+ if err := provider.Save(p); err != nil {
+ t.Fatal(err)
+ }
+ return p
+}
+
+// A MiniMax API key makes videos with H3, intl and CN alike, at its own
+// host; none of the H3 models is a chat model.
+func TestMiniMaxKeysMakeH3Videos(t *testing.T) {
+ fresh(t)
+ for _, preset := range []string{"minimax", "minimax-cn"} {
+ p, err := provider.FromPreset(preset)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p.ID, p.Key = preset, "key"
+ var ids []string
+ for _, m := range Videomakers(p) {
+ ids = append(ids, m.ID)
+ if !m.Films || m.Provider != preset {
+ t.Fatalf("%s: %+v isn't a video model of its", preset, m)
+ }
+ }
+ if strings.Join(ids, ",") != "MiniMax-H3,MiniMax-H3-Highspeed,MiniMax-H3-Lite,MiniMax-H3-Max" {
+ t.Fatalf("%s makes videos with %v", preset, ids)
+ }
+ if len(catalog.Chat(Videomakers(p))) != 0 {
+ t.Fatalf("%s: H3 is in the chat list", preset)
+ }
+ if len(customVideomakers(p)) != 0 {
+ t.Fatalf("%s is asked at an OpenAI videos API", preset)
+ }
+ }
+ if h := minimaxHost(provider.Provider{Chat: "https://api.minimax.io/v1"}); h != "https://api.minimax.io" {
+ t.Fatalf("intl host %q", h)
+ }
+ if h := minimaxHost(provider.Provider{Anthropic: "https://api.minimaxi.com/anthropic"}); h != "https://api.minimaxi.com" {
+ t.Fatalf("CN host %q", h)
+ }
+ if h := minimaxHost(provider.Provider{Chat: "https://api.minimax.cn/v1"}); h != "https://api.minimax.cn" {
+ t.Fatalf("CN docs host %q", h)
+ }
+ // another vendor, a relay serving MiniMax's models, a sign-in: none
+ for _, p := range []provider.Provider{
+ {ID: "x", Chat: "https://api.deepseek.com/v1", Key: "k"},
+ {ID: "relay", Chat: "https://relay.example.com/minimax/v1", Key: "k"},
+ } {
+ if filmsMiniMax(p) || len(Videomakers(p)) != 0 {
+ t.Fatalf("%s makes MiniMax videos", p.ID)
+ }
+ }
+}
+
+// The H3 models are listed as video models only: /v1/models gives them
+// "kind": "video" when asked for videomakers, and never as chat models.
+func TestMiniMaxH3IsNoChatModel(t *testing.T) {
+ fresh(t)
+ up := newFakeMiniMax(t)
+ minimaxProvider(t, "minimax", "minimax", up)
+ s := New()
+ _, obj, raw, _ := request(t, s, http.MethodGet, "/v1/models", "", "")
+ if strings.Contains(string(raw), "MiniMax-H3") {
+ t.Fatalf("chat list has H3: %s", raw)
+ }
+ _ = obj
+ got := 0
+ for _, m := range videomakerObjects(httptest.NewRequest(http.MethodGet, "/v1/models", nil)) {
+ if strings.HasPrefix(m["id"].(string), "minimax/MiniMax-H3") && m["kind"] == "video" {
+ got++
+ }
+ }
+ if got != 4 {
+ t.Fatalf("%d H3 video models listed", got)
+ }
+}
+
+// A video is started at MiniMax's create, asked after at its query until
+// it is made, and its MP4 fetched; the request's prompt, duration,
+// resolution, ratio and images reach MiniMax as its API takes them.
+func TestMiniMaxVideoIsStartedPolledAndFetched(t *testing.T) {
+ fresh(t)
+ up := newFakeMiniMax(t)
+ minimaxProvider(t, "minimax", "minimax", up)
+ s := New()
+ code, obj, raw, _ := request(t, s, http.MethodPost, "/v1/videos", "application/json", `{"model":"minimax/MiniMax-H3-Lite","prompt":"a magpie lands on a branch","seconds":6,"size":"854x480"}`)
+ if code != 200 || obj["status"] != "queued" || obj["model"] != "minimax/MiniMax-H3-Lite" {
+ t.Fatalf("create: %d %s", code, raw)
+ }
+ id, _ := obj["id"].(string)
+ if !strings.HasPrefix(id, "video_minimax.424010985738629.") || !strings.HasSuffix(id, "."+keyMark(provider.Provider{Key: "key"})) {
+ t.Fatalf("id %q", id)
+ }
+ for _, want := range []string{"queued", "in_progress"} {
+ code, obj, raw, _ = request(t, s, http.MethodGet, "/v1/videos/"+id, "", "")
+ if code != 200 || obj["status"] != want {
+ t.Fatalf("want %s: %d %s", want, code, raw)
+ }
+ }
+ code, obj, raw, _ = request(t, s, http.MethodGet, "/v1/videos/"+id, "", "")
+ if code != 200 || obj["status"] != "completed" || obj["seconds"] != "5" || obj["model"] != "minimax/MiniMax-H3" {
+ t.Fatalf("succeeded: %d %s", code, raw)
+ }
+ code, _, raw, head := request(t, s, http.MethodGet, "/v1/videos/"+id+"/content", "", "")
+ if code != 200 || string(raw) != "minimax-mp4-bytes" || head.Get("Content-Type") != "video/mp4" {
+ t.Fatalf("content: %d %q %v", code, raw, head)
+ }
+ paths, bodies, auth := up.seen()
+ if paths[0] != "POST /v2/video_generation" || auth[0] != "Bearer key" || paths[1] != "GET /v2/query/video_generation/424010985738629" || paths[len(paths)-1] != "GET /cdn/output.mp4" {
+ t.Fatalf("paths %v auth %v", paths, auth)
+ }
+ var sent map[string]any
+ json.Unmarshal([]byte(bodies[0]), &sent)
+ content, _ := sent["content"].([]any)
+ first, _ := content[0].(map[string]any)
+ if sent["model"] != "MiniMax-H3-Lite" || sent["duration"] != float64(6) || sent["resolution"] != "480P" || sent["ratio"] != "16:9" || len(content) != 1 || first["type"] != "text" || first["text"] != "a magpie lands on a branch" {
+ t.Fatalf("create body %s", bodies[0])
+ }
+ if _, ok := sent["callback_url"]; ok {
+ t.Fatalf("a callback was sent: %s", bodies[0])
+ }
+}
+
+// The first and last frames go as image_url items with their roles, and
+// no ratio (the video takes the image's); a duration under the model's
+// shortest is raised to it, and a resolution it doesn't make is its
+// nearest.
+func TestMiniMaxVideoBody(t *testing.T) {
+ png := picture{Mime: "image/png", Data: []byte("png")}
+ end := picture{URL: "https://example.com/end.png"}
+ b, err := minimaxVideoBody("MiniMax-H3-Max", filming{Prompt: "p", Seconds: "2", Size: "1920x1080", Start: &png, End: &end})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got struct {
+ Content []struct {
+ Type string `json:"type"`
+ ImageURL map[string]string `json:"image_url"`
+ Role string `json:"role"`
+ } `json:"content"`
+ Duration int `json:"duration"`
+ Resolution string `json:"resolution"`
+ Ratio *string
+ }
+ json.Unmarshal(b, &got)
+ if len(got.Content) != 3 || got.Content[1].Role != "first_frame" || got.Content[1].ImageURL["url"] != "data:image/png;base64,cG5n" || got.Content[2].Role != "last_frame" || got.Content[2].ImageURL["url"] != "https://example.com/end.png" {
+ t.Fatalf("frames: %s", b)
+ }
+ if got.Duration != 5 || got.Resolution != "768P" || strings.Contains(string(b), `"ratio"`) {
+ t.Fatalf("Max at 2s 1080p: %s", b)
+ }
+ // H3 makes 2K; past 15 seconds is 15; a ratio it doesn't take is its nearest
+ b, _ = minimaxVideoBody("MiniMax-H3", filming{Prompt: "p", Seconds: "40", Size: "1080x1920"})
+ if !strings.Contains(string(b), `"resolution":"2K"`) || !strings.Contains(string(b), `"duration":15`) || !strings.Contains(string(b), `"ratio":"9:16"`) {
+ t.Fatalf("H3 1080x1920: %s", b)
+ }
+ b, _ = minimaxVideoBody("MiniMax-H3", filming{Prompt: "p", Size: "3:2"})
+ if !strings.Contains(string(b), `"ratio":"4:3"`) && !strings.Contains(string(b), `"ratio":"16:9"`) || !strings.Contains(string(b), `"duration":5`) || !strings.Contains(string(b), `"resolution":"768P"`) {
+ t.Fatalf("H3 3:2: %s", b)
+ }
+ // references: adaptive (none sent) except Lite, which needs one
+ b, _ = minimaxVideoBody("MiniMax-H3", filming{Prompt: "p", References: []picture{png}})
+ if strings.Contains(string(b), `"ratio"`) || !strings.Contains(string(b), `"role":"reference_image"`) {
+ t.Fatalf("H3 references: %s", b)
+ }
+ b, _ = minimaxVideoBody("MiniMax-H3-Lite", filming{Prompt: "p", References: []picture{png}})
+ if !strings.Contains(string(b), `"ratio":"16:9"`) {
+ t.Fatalf("Lite references: %s", b)
+ }
+ // the caller's own resolution goes as said
+ b, _ = minimaxVideoBody("MiniMax-H3-Lite", filming{Prompt: "p", Extra: map[string]any{"resolution": "480p"}})
+ if !strings.Contains(string(b), `"resolution":"480P"`) {
+ t.Fatalf("own resolution: %s", b)
+ }
+ if _, err := minimaxVideoBody("MiniMax-H3", filming{Prompt: "p", Start: &png, References: []picture{png}}); err == nil {
+ t.Fatal("frames and references went together")
+ }
+}
+
+// A last frame in the request reaches MiniMax, JSON and multipart alike.
+func TestMiniMaxVideoTakesALastFrame(t *testing.T) {
+ fresh(t)
+ up := newFakeMiniMax(t)
+ minimaxProvider(t, "minimax", "minimax", up)
+ s := New()
+ code, _, raw, _ := request(t, s, http.MethodPost, "/v1/videos", "application/json", `{"model":"minimax/MiniMax-H3","prompt":"the kite falls","input_reference":"data:image/png;base64,cG5n","last_frame":"https://example.com/end.png"}`)
+ if code != 200 {
+ t.Fatalf("create: %d %s", code, raw)
+ }
+ _, bodies, _ := up.seen()
+ if !strings.Contains(bodies[0], `"role":"first_frame"`) || !strings.Contains(bodies[0], `"url":"https://example.com/end.png"},"role":"last_frame"`) && !strings.Contains(bodies[0], `"role":"last_frame"`) {
+ t.Fatalf("create body %s", bodies[0])
+ }
+ // frames and references together are turned away before MiniMax is asked
+ code, obj, raw, _ := request(t, s, http.MethodPost, "/v1/videos", "application/json", `{"model":"minimax/MiniMax-H3","prompt":"x","input_reference":"data:image/png;base64,cG5n","reference_images":["data:image/png;base64,cG5n"]}`)
+ if code != 400 || !strings.Contains(errorOf(obj), "not both") {
+ t.Fatalf("mixed: %d %s", code, raw)
+ }
+ if paths, _, _ := up.seen(); len(paths) != 1 {
+ t.Fatalf("MiniMax was asked: %v", paths)
+ }
+}
+
+// A bad key, an empty balance and refused content are each said for what
+// they are, with MiniMax's own words and status; so is a task that failed.
+func TestMiniMaxVideoFailuresSayWhy(t *testing.T) {
+ fresh(t)
+ up := newFakeMiniMax(t)
+ p := minimaxProvider(t, "minimax", "minimax", up)
+ s := New()
+ for _, c := range []struct {
+ prompt string
+ code int
+ says []string
+ }{
+ {"BROKE", 402, []string{"out of balance", "pay-as-you-go", "insufficient balance (1008)"}},
+ {"SENSITIVE", 422, []string{"sensitive content: change what the video asks for", "(1026)"}},
+ } {
+ code, obj, raw, _ := request(t, s, http.MethodPost, "/v1/videos", "application/json", `{"model":"minimax/MiniMax-H3","prompt":"`+c.prompt+`"}`)
+ for _, want := range c.says {
+ if code != c.code || !strings.Contains(errorOf(obj), want) {
+ t.Fatalf("%s: want %d %q, got %d %s", c.prompt, c.code, want, code, raw)
+ }
+ }
+ }
+ // the key turned away
+ p.Key = "bad-key"
+ if err := provider.Save(p); err != nil {
+ t.Fatal(err)
+ }
+ code, obj, raw, _ := request(t, s, http.MethodPost, "/v1/videos", "application/json", `{"model":"minimax/MiniMax-H3","prompt":"a kite"}`)
+ if code != 401 || !strings.Contains(errorOf(obj), "turned the API key away") || !strings.Contains(errorOf(obj), "(1004)") {
+ t.Fatalf("bad key: %d %s", code, raw)
+ }
+ p.Key = "key"
+ if err := provider.Save(p); err != nil {
+ t.Fatal(err)
+ }
+ // a task that failed says why, by its code
+ code, obj, raw, _ = request(t, s, http.MethodPost, "/v1/videos", "application/json", `{"model":"minimax/MiniMax-H3","prompt":"FAILING"}`)
+ if code != 200 {
+ t.Fatalf("create failing: %d %s", code, raw)
+ }
+ id := obj["id"].(string)
+ code, obj, raw, _ = request(t, s, http.MethodGet, "/v1/videos/"+id, "", "")
+ e, _ := obj["error"].(map[string]any)
+ if code != 200 || obj["status"] != "failed" || e["code"] != "1026" || !strings.Contains(e["message"].(string), "sensitive content") || !strings.Contains(e["message"].(string), "video description contains sensitive content") {
+ t.Fatalf("failed: %d %s", code, raw)
+ }
+ code, obj, raw, _ = request(t, s, http.MethodGet, "/v1/videos/"+id+"/content", "", "")
+ if code != 409 || !strings.Contains(errorOf(obj), "change what the video asks for") {
+ t.Fatalf("failed content: %d %s", code, raw)
+ }
+}
+
+// generate_video, with no model to name, makes its video with H3 when a
+// MiniMax key is all that makes videos; a task still queued when the call
+// has waited its time answers with the id to wait on, and asking again
+// while it is still queued says so again.
+func TestImageMCPMakesMiniMaxVideos(t *testing.T) {
+ fresh(t)
+ up := newFakeMiniMax(t)
+ minimaxProvider(t, "minimax-cn", "minimax-cn", up)
+ if m := AutoVideomaker(); m != "minimax-cn/MiniMax-H3" {
+ t.Fatalf("auto videomaker %q", m)
+ }
+ t.Setenv("MAGPIE_PUBLIC_URL", "")
+ s := New()
+ h := lanGuard(s.Handler())
+ was, wasPoll := imageMCPWithin, imageMCPPoll
+ t.Cleanup(func() { imageMCPWithin, imageMCPPoll = was, wasPoll })
+ imageMCPWithin, imageMCPPoll = 30*time.Millisecond, time.Millisecond
+ m := readImageReply(t, imagePost(h, "127.0.0.1:5000", imageToolCall(GenerateVideoTool, map[string]any{"prompt": "STUCK kite", "seconds": 4})))
+ text := m.Result.Content[0].Text
+ i := strings.Index(text, `"video_minimax-cn.424010985738699.`)
+ if m.Result.IsError || i < 0 || !strings.Contains(text, GenerationResultTool) {
+ t.Fatalf("still queued: %+v", m)
+ }
+ id := strings.Trim(strings.Fields(text[i:])[0], `".,`)
+ m = readImageReply(t, imagePost(h, "127.0.0.1:5000", imageToolCall(GenerationResultTool, map[string]any{"id": id})))
+ if m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, id) {
+ t.Fatalf("still queued again: %+v", m)
+ }
+ imageMCPWithin = time.Minute
+ m = readImageReply(t, imagePost(h, "127.0.0.1:5000", imageToolCall(GenerateVideoTool, map[string]any{"prompt": "a kite", "seconds": 4})))
+ urls := urlsIn(m.Result.Content[0].Text)
+ if m.Result.IsError || len(urls) != 1 || !strings.HasSuffix(urls[0], "/content") {
+ t.Fatalf("made: %+v", m)
+ }
+ if w := imageGet(h, "127.0.0.1:5000", urls[0]); w.Code != 200 || w.Body.String() != "minimax-mp4-bytes" {
+ t.Fatalf("content: %d %s", w.Code, w.Body.String())
+ }
+ paths, bodies, _ := up.seen()
+ if paths[0] != "POST /v2/video_generation" || !strings.Contains(bodies[0], `"duration":4`) || !strings.Contains(bodies[0], `"ratio":"16:9"`) {
+ t.Fatalf("paths %v body %s", paths, bodies[0])
+ }
+}
+
+// A subscription that makes videos keeps its place as the one a request
+// naming no model goes to: a MiniMax key, paid by the second, comes after.
+func TestMiniMaxComesAfterOtherVideomakers(t *testing.T) {
+ grokSignedIn(t)
+ newGrokMedia(t)
+ up := newFakeMiniMax(t)
+ minimaxProvider(t, "minimax", "minimax", up)
+ if m := AutoVideomaker(); !strings.HasPrefix(m, "grok/") {
+ t.Fatalf("auto videomaker %q", m)
+ }
+}
+
+// A key whose plan doesn't make H3 (a Token Plan's) hands the video to the
+// provider's next key.
+func TestMiniMaxVideoMovesPastATokenPlanKey(t *testing.T) {
+ fresh(t)
+ var mu sync.Mutex
+ var auth []string
+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ auth = append(auth, r.Header.Get("Authorization"))
+ mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ if r.Header.Get("Authorization") == "Bearer plan-key" {
+ w.WriteHeader(403)
+ io.WriteString(w, `{"type":"error","error":{"type":"permission_error","message":"token plan not support model (2061)","http_code":"403"}}`)
+ return
+ }
+ io.WriteString(w, minimaxVideoCreateResponse)
+ }))
+ t.Cleanup(up.Close)
+ was := isMiniMaxHost
+ t.Cleanup(func() { isMiniMaxHost = was })
+ host := strings.TrimPrefix(up.URL, "http://")
+ isMiniMaxHost = func(h string) bool { return h == host }
+ p, _ := provider.FromPreset("minimax")
+ p.ID, p.Key, p.Chat, p.Anthropic = "minimax", "plan-key", up.URL+"/v1", up.URL+"/anthropic"
+ p.Keys = []provider.KeyAccount{{Key: "plan-key"}, {Key: "payg-key"}}
+ if err := provider.Save(p); err != nil {
+ t.Fatal(err)
+ }
+ s := New()
+ code, obj, raw, _ := request(t, s, http.MethodPost, "/v1/videos", "application/json", `{"model":"minimax/MiniMax-H3","prompt":"a kite"}`)
+ if code != 200 || !strings.HasSuffix(obj["id"].(string), "."+keyMark(provider.Provider{Key: "payg-key"})) {
+ t.Fatalf("create: %d %s (asked with %v)", code, raw, auth)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if len(auth) != 2 || auth[0] != "Bearer plan-key" || auth[1] != "Bearer payg-key" {
+ t.Fatalf("asked with %v", auth)
+ }
+}
diff --git a/internal/imagemcp/imagemcp.go b/internal/imagemcp/imagemcp.go
index d2fa3a6a8..3fd77cffe 100644
--- a/internal/imagemcp/imagemcp.go
+++ b/internal/imagemcp/imagemcp.go
@@ -75,7 +75,7 @@ var (
var videoSchema = map[string]any{
"name": videoTool,
"description": "Generate a short video from a text prompt, optionally starting from an image to animate, with a video model set up in Magpie " +
- "(a Grok subscription's Grok Imagine, Volcengine Ark Agent Plan's Seedance, another Magpie's, or a provider whose model list marks video models). It takes from ten seconds to a few minutes, then the video is saved as an mp4 file in the project (" + VideoFolder +
+ "(a Grok subscription's Grok Imagine, Volcengine Ark Agent Plan's Seedance, a MiniMax API key's MiniMax H3, another Magpie's, or a provider whose model list marks video models). It takes from ten seconds to a few minutes, then the video is saved as an mp4 file in the project (" + VideoFolder +
"/ unless path says where) and its path is returned; when it is not ready within about 20 seconds, the answer is an id to wait on with " + resultTool + " instead. Describe the subject, the motion and the camera: what moves, how, and what the shot is.",
"inputSchema": map[string]any{
"type": "object",
diff --git a/internal/imagemcp/imagemcp_test.go b/internal/imagemcp/imagemcp_test.go
index c5d7758e8..5b8023f16 100644
--- a/internal/imagemcp/imagemcp_test.go
+++ b/internal/imagemcp/imagemcp_test.go
@@ -289,7 +289,7 @@ func TestVideoToolSaysEveryVideoModel(t *testing.T) {
if desc == "" {
t.Fatalf("no generate_video in %v", res)
}
- for _, want := range []string{"Grok", "Seedance", "another Magpie", "model list marks video models"} {
+ for _, want := range []string{"Grok", "Seedance", "MiniMax H3", "another Magpie", "model list marks video models"} {
if !strings.Contains(desc, want) {
t.Errorf("description leaves out %q: %s", want, desc)
}